DatabaseRegionObservation

DatabaseRegionObservation tracks changes in the results of database requests, and notifies each database transaction whenever the database changes.

For example:

let observation = DatabaseRegionObservation(tracking: Player.all)
let cancellable = try observation.start(
    in: dbQueue,
    onError: { error in ... },
    onChange: { (db: Database) in
        print("A modification of the player table has just been committed.")
    })
  • Creates a DatabaseRegionObservation which observes regions, and notifies whenever one of the observed regions is modified by a database transaction.

    For example, this sample code counts the number of a times the player table is modified:

    let observation = DatabaseRegionObservation(tracking: Player.all())
    
    var count = 0
    let cancellable = observation.start(
        in: dbQueue,
        onError: { error in ... },
        onChange: { _ in
            count += 1
            print("Players have been modified \(count) times.")
        }à
    

    The observation lasts until the cancellable returned by start is cancelled or deallocated.

  • Starts the observation in the provided database writer (such as a database queue or database pool), and returns a transaction observer.

    For example:

    let observation = DatabaseRegionObservation.tracking(Player.all())
    let cancellable = observation.start(
        in: dbQueue,
        onError: { error in ... },
        onChange: { (db: Database) in
            print("A modification of the player table has just been committed.")
        })
    

    If the start method is called from a writing database access method, the observation of impactful transactions starts immediately. Otherwise, it blocks the current thread until a write access can be established.