ValueObservation
extension ValueObservation
Combine extensions on ValueObservation.
-
Creates a publisher which tracks changes in database values.
For example:
let observation = ValueObservation.tracking { db in try Player.fetchAll(db) } let cancellable = observation .publisher(in: dbQueue) .sink( receiveCompletion: { completion in ... }, receiveValue: { players: [Player] in print("fresh players: \(players)") })
By default, fresh values are dispatched asynchronously on the main queue. You can change this behavior by by providing a scheduler.
For example,
.immediate
notifies all values on the main queue as well, and the first one is immediately notified when the publisher is subscribed:let cancellable = observation .publisher( in: dbQueue, scheduling: .immediate) // <- .sink( receiveCompletion: { completion in ... }, receiveValue: { players: [Player] in print("fresh players: \(players)") }) // <- here "fresh players" is already printed.
Note that the
.immediate
scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.Declaration
Swift
public func publisher( in reader: DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main)) -> DatabasePublishers.Value<Reducer.Value>
Parameters
reader
A DatabaseReader.
scheduler
A Scheduler. By default, fresh values are dispatched asynchronously on the main queue.
Return Value
A Combine publisher