diff --git a/Documentation/GRDB3MigrationGuide.md b/Documentation/GRDB3MigrationGuide.md index b4274728d..91a564f89 100644 --- a/Documentation/GRDB3MigrationGuide.md +++ b/Documentation/GRDB3MigrationGuide.md @@ -44,7 +44,7 @@ To guarantee asynchronous notifications, and never ever block your main thread, ```swift // On main queue -var observation = ValueObservation.trackingAll(Player.all()) +var observation = Player.observationForAll() observation.scheduling = .async(onQueue: .main, startImmediately: true) let observer = try observation.start(in: dbQueue) { (players: [Player]) in // On main queue diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift index 80994c37f..78c0e0266 100644 --- a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -65,8 +65,6 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: // MARK: - Observation - // TODO: add support for trackingOne as well - /// Creates a ValueObservation which observes *request*, and notifies /// fresh values whenever the request is modified by a /// database transaction. diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index fc940393b..967aabd04 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -11,7 +11,7 @@ public enum ValueScheduling { /// notified right upon subscription, synchronously: /// /// // On main queue - /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observation = Player.observationForAll() /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("fresh players: \(players)") /// } @@ -22,7 +22,7 @@ public enum ValueScheduling { /// /// // Not on the main queue: "fresh players" is eventually printed /// // on the main queue. - /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observation = Player.observationForAll() /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("fresh players: \(players)") /// } @@ -49,7 +49,7 @@ public enum ValueScheduling { /// the observation. /// /// // On any queue - /// var observation = ValueObservation.trackingAll(Player.all()) + /// var observation = Player.observationForAll() /// observation.scheduling = .unsafe(startImmediately: true) /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("fresh players: \(players)") @@ -68,7 +68,7 @@ public enum ValueScheduling { /// /// For example: /// -/// let observation = ValueObservation.trackingAll(Player.all) +/// let observation = Player.observationForAll() /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("Players have changed.") /// } @@ -98,7 +98,7 @@ public struct ValueObservation { /// notified right upon subscription, synchronously:: /// /// // On main queue - /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observation = Player.observationForAll() /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("fresh players: \(players)") /// } @@ -109,7 +109,7 @@ public struct ValueObservation { /// /// // Not on the main queue: "fresh players" is eventually printed /// // on the main queue. - /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observation = Player.observationForAll() /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("fresh players: \(players)") /// } @@ -135,7 +135,7 @@ public struct ValueObservation { /// the observation. /// /// // On any queue - /// var observation = ValueObservation.trackingAll(Player.all()) + /// var observation = Player.observationForAll() /// observation.scheduling = .unsafe(startImmediately: true) /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("fresh players: \(players)") @@ -207,9 +207,8 @@ extension ValueObservation where Reducer: ValueReducer { /// For example, the observation below notifies changes to a player if and /// only if it exists: /// - /// let request = Player.filter(key: 42) - /// let observation = ValueObservation - /// .trackingOne(request) + /// let observation = Player.filter(key: 42) + /// .observationForFirst() /// .compactMap { $0 } // filters out missing player /// /// The `fetchFirst` method thus returns nil if player does not exist: diff --git a/GRDB/ValueObservation/ValueReducer/Combine.swift b/GRDB/ValueObservation/ValueReducer/Combine.swift index a2259b533..178cc06fb 100644 --- a/GRDB/ValueObservation/ValueReducer/Combine.swift +++ b/GRDB/ValueObservation/ValueReducer/Combine.swift @@ -60,6 +60,18 @@ extension ValueObservation where Reducer == Void { } } +extension ValueObservation where Reducer: ValueReducer { + public func combine< + R1: ValueReducer, + Combined>( + _ other: ValueObservation, + _ transform: @escaping (Reducer.Value, R1.Value) -> Combined) + -> ValueObservation, Combined>> + { + return ValueObservation.combine(self, other).map(transform) + } +} + // MARK: - Combine 3 Reducers extension ValueReducers { @@ -134,6 +146,25 @@ extension ValueObservation where Reducer == Void { } } +extension ValueObservation where Reducer: ValueReducer { + public func combine< + R1: ValueReducer, + R2: ValueReducer, + Combined>( + _ observation1: ValueObservation, + _ observation2: ValueObservation, + _ transform: @escaping (Reducer.Value, R1.Value, R2.Value) -> Combined) + -> ValueObservation, Combined>> + { + return ValueObservation + .combine( + self, + observation1, + observation2) + .map(transform) + } +} + // MARK: - Combine 4 Reducers extension ValueReducers { @@ -220,6 +251,28 @@ extension ValueObservation where Reducer == Void { } } +extension ValueObservation where Reducer: ValueReducer { + public func combine< + R1: ValueReducer, + R2: ValueReducer, + R3: ValueReducer, + Combined>( + _ observation1: ValueObservation, + _ observation2: ValueObservation, + _ observation3: ValueObservation, + _ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value) -> Combined) + -> ValueObservation, Combined>> + { + return ValueObservation + .combine( + self, + observation1, + observation2, + observation3) + .map(transform) + } +} + // MARK: - Combine 5 Reducers extension ValueReducers { @@ -318,6 +371,31 @@ extension ValueObservation where Reducer == Void { } } +extension ValueObservation where Reducer: ValueReducer { + public func combine< + R1: ValueReducer, + R2: ValueReducer, + R3: ValueReducer, + R4: ValueReducer, + Combined>( + _ observation1: ValueObservation, + _ observation2: ValueObservation, + _ observation3: ValueObservation, + _ observation4: ValueObservation, + _ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value, R4.Value) -> Combined) + -> ValueObservation, Combined>> + { + return ValueObservation + .combine( + self, + observation1, + observation2, + observation3, + observation4) + .map(transform) + } +} + // MARK: - Combine 6 Reducers extension ValueReducers { diff --git a/README.md b/README.md index 7cbfa1190..f505fb2df 100644 --- a/README.md +++ b/README.md @@ -2916,8 +2916,7 @@ try dbQueue.read { db in ```swift // Observe changes -try ValueObservation - .trackingOne(Player.maximumScore) +try Player.maximumScore.observationForFirst() .start(in: dbQueue) { (maxScore: Int?) in print("The maximum score has changed") } @@ -4483,8 +4482,7 @@ When you also want to use database observation tools such as [ValueObservation], } // Observe with ValueObservation - try ValueObservation - .trackingOne(request) + try request.observationForFirst() .start(in: dbQueue) { (maxScore: Int?) in print("The maximum score has changed") } @@ -4582,8 +4580,7 @@ let player = try request.fetchOne(db) // Player? Those requests can feed [ValueObservation]: ```swift -try ValueObservation. - .trackingOne(Player.filter(key: 1)) +try Player.filter(key: 1).observationForFirst() .start(in: dbQueue) { (player: Player?) in print("Player 1 has changed") } @@ -6176,7 +6173,7 @@ class PlayerViewController: UIViewController { // Define a ValueObservation which tracks a player let request = Player.filter(key: 42) - let observation = ValueObservation.trackingOne(request) + let observation = request.observationForFirst() // Start observing the database observer = try! observation.start( @@ -6212,7 +6209,7 @@ The observer returned by the `start` method is stored in a property of the view > > // Define a ValueObservation which tracks a player > let request = Player.filter(key: 42) -> var observation = ValueObservation.trackingOne(request) +> var observation = request.observationForFirst() > > // Observation is asynchronous > observation.scheduling = .async(onQueue: .main, startImmediately: true) @@ -6246,7 +6243,7 @@ request.observationForFirst() Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request methods: -- `observationForCount` notifies counts: +- `observationForCount()` notifies counts: ```swift // Observe number of players @@ -6256,7 +6253,7 @@ Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request me } ``` -- `observationForAll` notifies arrays: +- `observationForAll()` notifies arrays: ```swift // Observe all players @@ -6273,7 +6270,7 @@ Those observations match the `fetchCount`, `fetchAll`, and `fetchOne` request me } ``` -- `observationForFirst` notifies optional values, built from a single database row (if any): +- `observationForFirst()` notifies optional values, built from a single database row (if any): ```swift // Observe a single player @@ -6446,9 +6443,8 @@ For example: ```swift // Observe a player's profile image -let observation = ValueObservation - .trackingOne(Player.filter(key: 42)) - .map { player in player?.loadBigProfileImage() } +let observation = Player.filter(key: 42).observationForFirst() + .map { player in player?.image } let observer = observation.start(in: dbQueue) { (image: UIImage?) in print("Player picture has changed") @@ -6466,8 +6462,7 @@ For example: ```swift // Observe a player -let observation = ValueObservation - .trackingOne(Player.filter(key: 42)) +let observation = Player.filter(key: 42).observationForFirst() .compactMap { $0 } let observer = observation.start(in: dbQueue) { (player: Player) in @@ -6485,8 +6480,7 @@ The `distinctUntilChanged` method filters out the consecutive equal values notif For example: ```swift -let observation = ValueObservation - .trackingOne(Player.filter(key: 42)) +let observation = Player.filter(key: 42).observationForFirst() .map { player in player != nil } // existence test .distinctUntilChanged() @@ -6504,33 +6498,50 @@ let observer = observation.start(in: dbQueue) { (exists: Bool) in #### ValueObservation.combine(...) -Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. +Sometimes you need to observe several requests at the same time. When this happens, **combine** several observations together with the `ValueObservation.combine(...)` method: ```swift -// The two observed requests (the team and its players) -let teamRequest = Team.filter(key: 1) -let playersRequest = Player.filter(Column("teamId") == 1) +struct HallOfFame { + /// Total number of players + var playerCount: Int + + /// The best ones + var bestPlayers: [Player] +} -// Two observations -let teamObservation = teamRequest.observationForFirst() -let playersObservation = playersRequest.observationForAll() +// The two base observations +let playerCountObservation = Player.observationForCount() +let bestPlayersObservation = Player + .limit(10) + .order(Column("score").desc) + .observationForAll() // The combined observation -let observation = ValueObservation.combine(teamObservation, playersObservation) +let observation = ValueObservation + .combine(playerCountObservation, bestPlayersObservation) + .map { HallOfFame(playerCount: $0, bestPlayers: $1) } -// Start tracking players and teams -let observer = observation.start(in: dbQueue) { (team: Team?, players: [Player]) in - print("Team or players have changed.") +// Start tracking the hall of fame +let observer = observation.start(in: dbQueue) { (hallOfFame: HallOfFame) in + print("The hall of fame has changed.") } ``` +`combine` also exists as an instance method: + +```swift +let observation = playerCountObservation.combine(bestPlayersObservation) { + HallOfFame(playerCount: $0, bestPlayers: $1) +} +``` + +You can combine up to eight observations together. They can feed from as many database tables as needed. + Combining observations provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)). -> :point_up: **Note**: you can combine up to eight observations together. If you need more, combine several combined observations, or please submit a pull request. -> -> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the `ValueObservation.combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [RxGRDB], compose observations with `ValueObservation.combine`, not with the CombineLatest operator. +> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the ValueObservation `combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [RxGRDB] or [Combine], make sure you compose observations with `ValueObservation.combine`, not with the CombineLatest operator. ### ValueObservation Error Handling @@ -8846,3 +8857,4 @@ This chapter has been renamed [Beyond FetchableRecord]. [DatabaseRegion]: #databaseregion [SQL Interpolation]: Documentation/SQLInterpolation.md [custom SQLite build]: Documentation/CustomSQLiteBuilds.md +[Combine]: https://developer.apple.com/documentation/combine diff --git a/Tests/GRDBTests/ValueObservationCombineTests.swift b/Tests/GRDBTests/ValueObservationCombineTests.swift index 77aaafce4..a4e5e2e42 100644 --- a/Tests/GRDBTests/ValueObservationCombineTests.swift +++ b/Tests/GRDBTests/ValueObservationCombineTests.swift @@ -822,4 +822,64 @@ class ValueObservationCombineTests: GRDBTestCase { _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } XCTAssertNotNil(value) } + + func testHeterogeneusCombined2() throws { + struct V1 { } + struct V2 { } + struct Combined { } + let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) + let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) + let observation = observation1.combine(observation2) { (v1: V1, v2: V2) -> Combined in Combined() } + var value: Combined? + _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } + XCTAssertNotNil(value) + } + + func testHeterogeneusCombined3() throws { + struct V1 { } + struct V2 { } + struct V3 { } + struct Combined { } + let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) + let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) + let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) + let observation = observation1.combine(observation2, observation3) { (v1: V1, v2: V2, v3: V3) -> Combined in Combined() } + var value: Combined? + _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } + XCTAssertNotNil(value) + } + + func testHeterogeneusCombined4() throws { + struct V1 { } + struct V2 { } + struct V3 { } + struct V4 { } + struct Combined { } + let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) + let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) + let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) + let observation4 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V4() }) + let observation = observation1.combine(observation2, observation3, observation4) { (v1: V1, v2: V2, v3: V3, v4: V4) -> Combined in Combined() } + var value: Combined? + _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } + XCTAssertNotNil(value) + } + + func testHeterogeneusCombined5() throws { + struct V1 { } + struct V2 { } + struct V3 { } + struct V4 { } + struct V5 { } + struct Combined { } + let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) + let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) + let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) + let observation4 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V4() }) + let observation5 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V5() }) + let observation = observation1.combine(observation2, observation3, observation4, observation5) { (v1: V1, v2: V2, v3: V3, v4: V4, v5: V5) -> Combined in Combined() } + var value: Combined? + _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } + XCTAssertNotNil(value) + } }