Static Methodgrdb 7.3.0GRDB

tracking(_:)

Creates a ValueObservation that notifies the fetched values whenever it changes.

ValueObservation.swift:982
@preconcurrency static func tracking<Value>(_ fetch: @escaping (Database) throws -> Value) -> ValueObservation<Reducer> where Reducer == ValueReducers.Fetch<Value>, Value : Sendable

Parameters

fetch

The closure that fetches the observed value.

For example:

let observation = ValueObservation.tracking { db in
    try Player.fetchAll(db)
}

let cancellable = try observation.start(in: dbQueue) { error in
    // handle error
} onChange: { (players: [Player]) in
    print("Players have changed")
}

An observation can perform multiple requests, from multiple database tables, and even use raw SQL:

struct HallOfFame {
    var totalPlayerCount: Int
    var bestPlayers: [Player]
}

// An observation of HallOfFame
let observation = ValueObservation.tracking { db -> HallOfFame in
    let totalPlayerCount = try Player.fetchCount(db)

    let bestPlayers = try Player
        .order(Column("score").desc)
        .limit(10)
        .fetchAll(db)

    return HallOfFame(
        totalPlayerCount: totalPlayerCount,
        bestPlayers: bestPlayers)
}

// An observation of the maximum score
let observation = ValueObservation.tracking { db in
    try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player")
}