SharedValueObservation

public final class SharedValueObservation<Element>

Experimental

A shared value observation that shares a single underlying database observation for all subscriptions, and thus spares database resources.

For example:

let sharedObservation = ValueObservation
    .tracking { db in try Player.fetchAll(db) }
    .shared(in: dbQueue)

let cancellable = try sharedObservation.start(
    onError: { error in ... },
    onChange: { players: [Player] in
        print("Players have changed.")
    })

The sharing only applies if you start observing the database from the same SharedValueObservation instance:

// NOT shared
let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)

// Shared
let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue)
let cancellable1 = sharedObservation.start(...)
let cancellable2 = sharedObservation.start(...)
  • Starts observing the database.

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

    For example:

    let sharedObservation = ValueObservation
        .tracking { db in try Player.fetchAll(db) }
        .shared(in: dbQueue)
    
    let cancellable = try sharedObservation.start(
        onError: { error in ... },
        onChange: { players: [Player] in
            print("fresh players: \(players)")
        })
    

    Declaration

    Swift

    public func start(
        onError: @escaping (Error) -> Void,
        onChange: @escaping (Element) -> Void)
    -> DatabaseCancellable

    Parameters

    onError

    A closure that is provided eventual errors that happen during observation

    onChange

    A closure that is provided fresh values

    Return Value

    a DatabaseCancellable

  • Creates a publisher which tracks changes in database values.

    For example:

    let publisher = ValueObservation
        .tracking { db in try Player.fetchAll(db) }
        .shared(in: dbQueue)
        .publisher()
    
    let cancellable = publisher.sink(
        receiveCompletion: { completion in ... },
        receiveValue: { players: [Player] in
            print("fresh players: \(players)")
        })
    

    Declaration

    Swift

    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public func publisher() -> DatabasePublishers.Value<Element>

    Return Value

    A Combine publisher

Asynchronous Observation