diff --git a/CHANGELOG.md b/CHANGELOG.md index 681ec34fd..eb1960cc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#723](https://github.com/groue/GRDB.swift/pull/723): SE-0255: Implicit returns from single-expression functions - [#724](https://github.com/groue/GRDB.swift/pull/724): SE-0242: Synthesize default values for the memberwise initializer - [#728](https://github.com/groue/GRDB.swift/pull/728): Make ValueObservation error handling mandatory +- [#729](https://github.com/groue/GRDB.swift/pull/729): ValueObservation always emits an initial value ## 4.11.0 diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index f58e47176..a9450bbe5 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -122,37 +122,51 @@ extension DatabaseSnapshot { onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - // TODO: fetch asynchronously when possible - do { - // Deal with initial value - switch observation.scheduling { - case .mainQueue: - if let value = try unsafeReentrantRead(observation.fetchFirst) { - if DispatchQueue.isMain { + switch observation.scheduling { + case .mainQueue: + if DispatchQueue.isMain { + do { + if let value = try read(observation.fetchFirst) { onChange(value) - } else { - DispatchQueue.main.async { - onChange(value) - } } + } catch { + onError(error) } - case let .async(onQueue: queue, startImmediately: startImmediately): - if startImmediately { - if let value = try unsafeReentrantRead(observation.fetchFirst) { - queue.async { - onChange(value) + } else { + serializedDatabase.async { db in + let result = Result { try observation.fetchFirst(db) } + DispatchQueue.main.async { + do { + if let value = try result.get() { + onChange(value) + } + } catch { + onError(error) } } } - case let .unsafe(startImmediately: startImmediately): - if startImmediately { - if let value = try unsafeReentrantRead(observation.fetchFirst) { - onChange(value) - } - } } - } catch { - onError(error) + case let .async(onQueue: queue): + serializedDatabase.async { db in + let result = Result { try observation.fetchFirst(db) } + queue.async { + do { + if let value = try result.get() { + onChange(value) + } + } catch { + onError(error) + } + } + } + case .unsafe: + do { + if let value = try unsafeReentrantRead(observation.fetchFirst) { + onChange(value) + } + } catch { + onError(error) + } } // Return a dummy observer, because snapshots never change diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 4a2b069f5..4555a078a 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -277,7 +277,7 @@ extension DatabaseWriter { /// Default implementation for the DatabaseReader requirement. /// :nodoc: public func remove(transactionObserver: TransactionObserver) { - writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } + unsafeReentrantWrite { $0.remove(transactionObserver: transactionObserver) } } // MARK: - Erasing the content of the database @@ -310,114 +310,104 @@ extension DatabaseWriter { onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - let requiresWriteAccess = observation.requiresWriteAccess - let observer = ValueObserver( - requiresWriteAccess: requiresWriteAccess, - observesSelectedRegion: observation.observesSelectedRegion, - writer: self, - reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"), - onError: onError, - onChange: onChange) + // True if initial value must be sent to the onChange callback + // before this method returns. + let initialSync: Bool + + // The queue for other values. Nil for any queue. + let notificationQueue: DispatchQueue? switch observation.scheduling { case .mainQueue: if DispatchQueue.isMain { // Use case: observation starts on the main queue and wants - // a synchronous initial fetch. Typically, this helps avoiding - // flashes of missing content. - var startValue: Reducer.Value? = nil - defer { - if let startValue = startValue { - onChange(startValue) - } - } - - do { - try unsafeReentrantWrite { db in - observer.notificationQueue = DispatchQueue.main - observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) - observer.reducer = try observation.makeReducer(db) - - // Initial value & selected region - let fetchedValue: Reducer.Fetched - if observation.observesSelectedRegion { - (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { - try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - } else { - fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - if let value = observer.reducer.value(fetchedValue) { - startValue = value - } - - db.add(transactionObserver: observer, extent: .observerLifetime) - } - } catch { - onError(error) - } + // a synchronous initial fetch. This helps avoiding flashes of + // missing content. + initialSync = true + notificationQueue = DispatchQueue.main } else { + // TODO: make this a fatal error when .mainQueue is no longer + // the default scheduling. // Use case: observation does not start on the main queue, but // has the default scheduling .mainQueue - asyncWriteWithoutTransaction { db in - do { - observer.notificationQueue = DispatchQueue.main - observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) - observer.reducer = try observation.makeReducer(db) - - // Initial value & selected region - let fetchedValue: Reducer.Fetched - if observation.observesSelectedRegion { - (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { - try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - } else { - fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - if let value = observer.reducer.value(fetchedValue) { - DispatchQueue.main.async { - onChange(value) - } - } - - db.add(transactionObserver: observer, extent: .observerLifetime) - } catch { - DispatchQueue.main.async { - onError(error) - } - } - } + initialSync = false + notificationQueue = DispatchQueue.main } - case let .async(onQueue: queue, startImmediately: startImmediately): + case let .async(onQueue: queue): // Use case: observation must not block the target queue - asyncWriteWithoutTransaction { db in - do { - observer.notificationQueue = queue + initialSync = false + notificationQueue = queue + + case .unsafe: + // Use case: third-party integration (RxSwift, Combine, ...) that + // need a synchronous initial fetch. + // + // This is really super extra unsafe. + // + // If the observation is started on one dispatch queue, then + // the onChange and onError callbacks must be asynchronously + // dispatched on the *same* queue. + // + // A failure to follow this rule may mess with the ordering of + // initial values. + initialSync = true + notificationQueue = nil + } + + // --- + + let observer = ValueObserver( + requiresWriteAccess: observation.requiresWriteAccess, + observesSelectedRegion: observation.observesSelectedRegion, + writer: self, + notificationQueue: notificationQueue, + reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"), + onError: onError, + onChange: onChange) + + // Fetch initial value, with two side effects: + // - observer.selectedRegion is set if observation.observesSelectedRegion + // - observer.reducer moves forward + func fetchInitialValue(_ db: Database) throws -> Reducer.Value? { + let fetchedValue: Reducer.Fetched + let requiresWriteAccess = observation.requiresWriteAccess + if observation.observesSelectedRegion { + (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { + try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + } else { + fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + } + return observer.reducer.value(fetchedValue) + } + + if initialSync { + do { + // TODO: make initialValue non-optional when compactMap is removed. + let initialValue: Reducer.Value? = try unsafeReentrantWrite { db in observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) observer.reducer = try observation.makeReducer(db) - - // Initial value & selected region - if startImmediately { - let fetchedValue: Reducer.Fetched - if observation.observesSelectedRegion { - (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { - try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - } else { - fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - if let value = observer.reducer.value(fetchedValue) { - queue.async { - onChange(value) - } - } - } else if observation.observesSelectedRegion { - (_, observer.selectedRegion) = try db.recordingSelectedRegion { - try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + let initialValue = try fetchInitialValue(db) + db.add(transactionObserver: observer, extent: .observerLifetime) + return initialValue + } + if let initialValue = initialValue { + onChange(initialValue) + } + } catch { + onError(error) + } + } else if let queue = notificationQueue { + asyncWriteWithoutTransaction { db in + do { + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) + if let value = try fetchInitialValue(db) { + queue.async { + onChange(value) } } - db.add(transactionObserver: observer, extent: .observerLifetime) } catch { queue.async { @@ -425,80 +415,18 @@ extension DatabaseWriter { } } } - - case let .unsafe(startImmediately: startImmediately): - if startImmediately { - // Use case: third-party integration (RxSwift, Combine, ...) that - // need a synchronous initial fetch. - // - // This is really super extra unsafe. - // - // If the observation is started on one dispatch queue, then - // the onChange and onError callbacks must be asynchronously - // dispatched on the *same* queue. - // - // A failure to follow this rule may mess with the ordering of - // initial values. - var startValue: Reducer.Value? = nil - defer { - if let startValue = startValue { - onChange(startValue) - } - } - + } else { + asyncWriteWithoutTransaction { db in do { - try unsafeReentrantWrite { db in - observer.notificationQueue = nil - observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) - observer.reducer = try observation.makeReducer(db) - - // Initial value & selected region - if startImmediately { - let fetchedValue: Reducer.Fetched - if observation.observesSelectedRegion { - (fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion { - try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - } else { - fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - if let value = observer.reducer.value(fetchedValue) { - startValue = value - } - } else if observation.observesSelectedRegion { - (_, observer.selectedRegion) = try db.recordingSelectedRegion { - try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - } - - db.add(transactionObserver: observer, extent: .observerLifetime) + observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) + observer.reducer = try observation.makeReducer(db) + if let value = try fetchInitialValue(db) { + onChange(value) } + db.add(transactionObserver: observer, extent: .observerLifetime) } catch { onError(error) } - } else { - // Use case: ? - // - // This is unsafe because no promise is made on the dispatch - // queue on which the onChange and onError callbacks are called. - asyncWriteWithoutTransaction { db in - do { - observer.notificationQueue = nil - observer.baseRegion = try observation.baseRegion(db).ignoringViews(db) - observer.reducer = try observation.makeReducer(db) - - // Selected region - if observation.observesSelectedRegion { - (_, observer.selectedRegion) = try db.recordingSelectedRegion { - try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) - } - } - - db.add(transactionObserver: observer, extent: .observerLifetime) - } catch { - onError(error) - } - } } } diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index e0dfce9a8..f8d1e29c7 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -193,6 +193,9 @@ extension ValueReducer where Value: Equatable { { preconditionFailure() } } +@available(*, unavailable, renamed: "ValueObservationScheduling") +typealias ValueScheduling = ValueObservationScheduling + #if SQLITE_HAS_CODEC extension Configuration { @available(*, unavailable, message: "Use Database.usePassphrase(_:) in Configuration.prepareDatabase instead.") diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 975929f31..9cdb863d5 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -2,12 +2,12 @@ import Dispatch // MARK: - ValueScheduling -/// ValueScheduling controls how ValueObservation schedules the notifications -/// of fresh values to your application. -public enum ValueScheduling { +/// ValueObservationScheduling controls how ValueObservation schedules the +/// fresh values to your application. +public enum ValueObservationScheduling { /// All values are notified on the main queue. /// - /// If the observation starts on the main queue, an initial value is + /// If the observation starts on the main queue, the initial value is /// notified right upon subscription, synchronously: /// /// // On main queue @@ -17,7 +17,7 @@ public enum ValueScheduling { /// } /// // <- here "fresh players" is already printed. /// - /// If the observation does not start on the main queue, an initial value + /// If the observation does not start on the main queue, the initial value /// is also notified on the main queue, but asynchronously: /// /// // Not on the main queue: "fresh players" is eventually printed @@ -37,20 +37,16 @@ public enum ValueScheduling { case mainQueue /// All values are asychronously notified on the specified queue. - /// - /// An initial value is fetched and notified if `startImmediately` - /// is true. - case async(onQueue: DispatchQueue, startImmediately: Bool) + case async(onQueue: DispatchQueue) /// Values are not all notified on the same dispatch queue. /// - /// If `startImmediately` is true, an initial value is notified right upon - /// subscription, synchronously, on the dispatch queue which starts - /// the observation. + /// The initial value is notified right upon subscription, synchronously, on + /// the dispatch queue which starts the observation. /// /// // On any queue /// var observation = Player.observationForAll() - /// observation.scheduling = .unsafe(startImmediately: true) + /// observation.scheduling = .unsafe /// let observer = try observation.start(in: dbQueue) { players: [Player] in /// print("fresh players: \(players)") /// } @@ -58,7 +54,7 @@ public enum ValueScheduling { /// /// When the database changes, other values are notified on /// unspecified queues. - case unsafe(startImmediately: Bool) + case unsafe } // MARK: - ValueObservation @@ -73,6 +69,8 @@ public enum ValueScheduling { /// print("Players have changed.") /// } public struct ValueObservation { + // TODO: all calls to this closure are followed by ignoringViews(). + // We should embed this ignoringViews() call. /// A closure that is evaluated when the observation starts, and returns /// a "base" observed database region. /// @@ -97,60 +95,7 @@ public struct ValueObservation { /// `scheduling` controls how fresh values are notified. Default /// is `.mainQueue`. - /// - /// - `.mainQueue`: all values are notified on the main queue. - /// - /// If the observation starts on the main queue, an initial value is - /// notified right upon subscription, synchronously:: - /// - /// // On main queue - /// let observation = Player.observationForAll() - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// If the observation does not start on the main queue, an initial - /// value is also notified on the main queue, but asynchronously: - /// - /// // Not on the main queue: "fresh players" is eventually printed - /// // on the main queue. - /// let observation = Player.observationForAll() - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// - /// When the database changes, fresh values are asynchronously notified: - /// - /// // Eventually prints "fresh players" on the main queue - /// try dbQueue.write { db in - /// try Player(...).insert(db) - /// } - /// - /// - `.onQueue(_:startImmediately:)`: all values are asychronously notified - /// on the specified queue. - /// - /// An initial value is fetched and notified if `startImmediately` - /// is true. - /// - /// - `unsafe(startImmediately:)`: values are not all notified on the same - /// dispatch queue. - /// - /// If `startImmediately` is true, an initial value is notified right - /// upon subscription, synchronously, on the dispatch queue which starts - /// the observation. - /// - /// // On any queue - /// var observation = Player.observationForAll() - /// observation.scheduling = .unsafe(startImmediately: true) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// When the database changes, other values are notified on - /// unspecified queues. - public var scheduling: ValueScheduling + public var scheduling: ValueObservationScheduling } extension ValueObservation where Reducer: ValueReducer { @@ -178,6 +123,7 @@ extension ValueObservation where Reducer: ValueReducer { // TODO: make public if it helps fetching an initial value before starting // the observation, in order to avoid waiting for long write transactions to // complete. + // TODO: make the result non-optional when compactMap is removed. /// Returns the observed value. /// /// This method returns nil if observation would not notify any diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 232d9de7a..943ca1bc0 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -3,10 +3,9 @@ import Foundation /// Support for ValueObservation. /// See DatabaseWriter.add(observation:onError:onChange:) class ValueObserver: TransactionObserver { - // Reducer and notificationQueue must be set before observer is + // Reducer must be set before observer is // added to a database. var reducer: Reducer! - var notificationQueue: DispatchQueue? var baseRegion = DatabaseRegion() { didSet { observedRegion = baseRegion.union(selectedRegion) } @@ -15,9 +14,10 @@ class ValueObserver: TransactionObserver { didSet { observedRegion = baseRegion.union(selectedRegion) } } var observedRegion: DatabaseRegion! // internal for testability - private var requiresWriteAccess: Bool - private var observesSelectedRegion: Bool - private unowned var writer: DatabaseWriter + private let requiresWriteAccess: Bool + private let observesSelectedRegion: Bool + private unowned let writer: DatabaseWriter + private let notificationQueue: DispatchQueue? private let reduceQueue: DispatchQueue private let onError: (Error) -> Void private let onChange: (Reducer.Value) -> Void @@ -28,6 +28,7 @@ class ValueObserver: TransactionObserver { requiresWriteAccess: Bool, observesSelectedRegion: Bool, writer: DatabaseWriter, + notificationQueue: DispatchQueue?, reduceQueue: DispatchQueue, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) @@ -35,6 +36,7 @@ class ValueObserver: TransactionObserver { self.writer = writer self.requiresWriteAccess = requiresWriteAccess self.observesSelectedRegion = observesSelectedRegion + self.notificationQueue = notificationQueue self.reduceQueue = reduceQueue self.onError = onError self.onChange = onChange @@ -84,7 +86,6 @@ class ValueObserver: TransactionObserver { future = DatabaseFuture(.failure(error)) } } else { - // Synchronous read/write fetch future = DatabaseFuture(Result { var fetchedValue: Reducer.Fetched! try db.inTransaction { @@ -128,6 +129,7 @@ class ValueObserver: TransactionObserver { func reduce(future: DatabaseFuture) { do { if let value = try reducer.value(future.wait()) { + if self.isCancelled { return } if let queue = notificationQueue { queue.async { [weak self] in guard let self = self else { return } diff --git a/README.md b/README.md index e356827ef..e812393d2 100644 --- a/README.md +++ b/README.md @@ -5529,9 +5529,9 @@ try dbQueue.write { db in ## ValueObservation -**ValueObservation tracks changes in the results of database [requests](#requests), and notifies fresh values whenever the database changes.** +**ValueObservation tracks changes in database [requests](#requests), and notifies fresh values whenever the database changes.** -Changes are only notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). +Changes are notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). - **[ValueObservation Usage](#valueobservation-usage)** @@ -5585,7 +5585,7 @@ class PlayerViewController: UIViewController { By default, all values and errors are notified on the main queue. Views can be updated right from the `onChange` callback. -By default, an initial fetch is performed as soon as the observation starts: the view is set up and ready when the `viewWillAppear` method returns. +An initial fetch is performed as soon as the observation starts: the view is set up and ready when the `viewWillAppear` method returns. The observer returned by the `start` method is stored in a property of the view controller. This allows the view controller to control the duration of the observation. When the observer is deallocated, the observation stops. Meanwhile, all transactions that modify the observed player are notified, and the `nameLabel` is kept up-to-date. @@ -5603,7 +5603,7 @@ The observer returned by the `start` method is stored in a property of the view > } > > // Observation is asynchronous -> observation.scheduling = .async(onQueue: .main, startImmediately: true) +> observation.scheduling = .async(onQueue: .main) > > // Start observing the database > observer = observation.start( @@ -5649,7 +5649,7 @@ observer = observation.start( **You can observe several requests and several tables if you need**: all writes that have an impact on the fetched values will trigger the observation, and call the `onChange` function. -**It may happen that such an observation notifies identical consecutive values.** This is because it will fetch a fresh value whenever a change *could* happen. For example, the observation for the maximum player score will notify a fresh value every time a score is changed, inserted, or deleted, even if the maximum score is unchanged: +**The observation may notify identical consecutive values.** This is because it will fetch a fresh value whenever a change *could* happen. For example, the observation for the maximum player score will notify a fresh value every time a score is changed, inserted, or deleted, even if the maximum score is unchanged: ```swift // Track changes in the maximum player score @@ -5659,7 +5659,7 @@ let observation = ValueObservation.tracking { db in } ``` -You can filter out those duplicates with the [ValueObservation.removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: +You can filter out those duplicates with the [removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol: ```swift let observation = ValueObservation @@ -5907,7 +5907,7 @@ The `scheduling` property lets you control how fresh values are notified: - `.mainQueue` (the default): all values are notified on the main queue. - If the observation starts on the main queue, an initial value is notified right upon subscription, synchronously: + If the observation starts on the main queue, the initial value is notified right upon subscription, synchronously: ```swift // On main queue @@ -5921,7 +5921,7 @@ The `scheduling` property lets you control how fresh values are notified: // <- Here "fresh value" is already printed. ``` - If the observation does not start on the main queue, an initial value is also notified on the main queue, but asynchronously: + If the observation does not start on the main queue, the initial value is also notified on the main queue, but asynchronously: ```swift // Not on the main queue @@ -5941,16 +5941,14 @@ The `scheduling` property lets you control how fresh values are notified: // <- Eventually prints "fresh value" on the main queue ``` -- `.async(onQueue:startImmediately:)`: all values are asynchronously notified on the specified queue. - - An initial value is fetched and notified if `startImmediately` is true. +- `.async(onQueue:)`: all values, including the initial value, are asynchronously notified on the specified queue. For example: ```swift // On main queue var observation = ... - observation.scheduling = .async(onQueue: .main, startImmediately: true) + observation.scheduling = .async(onQueue: .main) let observer = observation.start( in: dbQueue, onError: { error in ... }, @@ -5961,14 +5959,14 @@ The `scheduling` property lets you control how fresh values are notified: // <- Eventually prints "fresh value" ``` -- `unsafe(startImmediately:)`: values are not all notified on the same dispatch queue. +- `unsafe`: values are not all notified on the same dispatch queue. - If `startImmediately` is true, an initial value is notified right upon subscription, synchronously, on the dispatch queue which starts the observation. + The initial value is notified right upon subscription, synchronously, on the dispatch queue which starts the observation. ```swift // On any queue var observation = ... - observation.scheduling = .unsafe(startImmediately: true) + observation.scheduling = .unsafe let observer = observation.start( in: dbQueue, onError: { error in ... }, diff --git a/Tests/GRDBTests/ValueObservationCompactMapTests.swift b/Tests/GRDBTests/ValueObservationCompactMapTests.swift index 325242ae9..6c39d07c4 100644 --- a/Tests/GRDBTests/ValueObservationCompactMapTests.swift +++ b/Tests/GRDBTests/ValueObservationCompactMapTests.swift @@ -64,7 +64,7 @@ class ValueObservationCompactMapTests: GRDBTestCase { func testCompactMapPreservesConfiguration() { var observation = ValueObservation.tracking(DatabaseRegion(), fetch: { _ in }) observation.requiresWriteAccess = true - observation.scheduling = .unsafe(startImmediately: true) + observation.scheduling = .unsafe let mappedObservation = observation.compactMap { _ in } XCTAssertEqual(mappedObservation.requiresWriteAccess, observation.requiresWriteAccess) diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift index d3ad09fb5..dde50ec4e 100644 --- a/Tests/GRDBTests/ValueObservationMapTests.swift +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -61,7 +61,7 @@ class ValueObservationMapTests: GRDBTestCase { func testMapPreservesConfiguration() { var observation = ValueObservation.tracking(DatabaseRegion(), fetch: { _ in }) observation.requiresWriteAccess = true - observation.scheduling = .unsafe(startImmediately: true) + observation.scheduling = .unsafe let mappedObservation = observation.map { _ in } XCTAssertEqual(mappedObservation.requiresWriteAccess, observation.requiresWriteAccess) diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index a9b40a3a9..a132aee8c 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -438,75 +438,88 @@ class ValueObservationReducerTests: GRDBTestCase { } } - // TODO: make this test pass reliably -// func testObserverInvalidation1() throws { -// func test(_ dbWriter: DatabaseWriter) throws { -// try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } -// -// let notificationExpectation = expectation(description: "notification") -// notificationExpectation.isInverted = true -// -// do { -// var observer: TransactionObserver? = nil -// _ = observer // Avoid "Variable 'observer' was written to, but never read" warning -// var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in -// AnyValueReducer( -// fetch: { _ in observer = nil /* deallocation */ }, -// value: { _ in () }) -// }) -// observation.scheduling = .unsafe(startImmediately: false) -// observer = observation.start( -// in: dbWriter, -// onError: { error in XCTFail("Unexpected error: \(error)") }, -// onChange: { count in -// XCTFail("unexpected change notification: \(String(describing: observer))") -// notificationExpectation.fulfill() -// }) -// } -// -// try dbWriter.write { db in -// try db.execute(sql: "INSERT INTO t DEFAULT VALUES") -// } -// waitForExpectations(timeout: 0.1, handler: nil) -// } -// -// try test(makeDatabaseQueue()) -// try test(makeDatabasePool()) -// } + func testObserverInvalidation1() throws { + // Test that observation stops when observer is deallocated + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.isInverted = true + notificationExpectation.expectedFulfillmentCount = 2 + + do { + var observer: TransactionObserver? = nil + _ = observer // Avoid "Variable 'observer' was written to, but never read" warning + var shouldStopObservation = false + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in + AnyValueReducer( + fetch: { _ in + if shouldStopObservation { + observer = nil /* deallocation */ + } + shouldStopObservation = true + }, + value: { _ in () }) + }) + observation.scheduling = .unsafe + observer = observation.start( + in: dbWriter, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + notificationExpectation.fulfill() + }) + } + + try dbWriter.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + waitForExpectations(timeout: 0.2, handler: nil) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } - // TODO: make this test pass reliably -// func testObserverInvalidation2() throws { -// func test(_ dbWriter: DatabaseWriter) throws { -// try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } -// -// let notificationExpectation = expectation(description: "notification") -// notificationExpectation.isInverted = true -// -// do { -// var observer: TransactionObserver? = nil -// _ = observer // Avoid "Variable 'observer' was written to, but never read" warning -// var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in -// AnyValueReducer( -// fetch: { _ in }, -// value: { _ in observer = nil /* deallocation right before notification */ }) -// }) -// observation.scheduling = .unsafe(startImmediately: false) -// observer = observation.start( -// in: dbWriter, -// onError: { error in XCTFail("Unexpected error: \(error)") }, -// onChange: { count in -// XCTFail("unexpected change notification: \(String(describing: observer))") -// notificationExpectation.fulfill() -// }) -// } -// -// try dbWriter.write { db in -// try db.execute(sql: "INSERT INTO t DEFAULT VALUES") -// } -// waitForExpectations(timeout: 0.1, handler: nil) -// } -// -// try test(makeDatabaseQueue()) -// try test(makeDatabasePool()) -// } + func testObserverInvalidation2() throws { + // Test that observation stops when observer is deallocated + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.isInverted = true + notificationExpectation.expectedFulfillmentCount = 2 + + do { + var observer: TransactionObserver? = nil + _ = observer // Avoid "Variable 'observer' was written to, but never read" warning + var shouldStopObservation = false + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in + AnyValueReducer( + fetch: { _ in }, + value: { _ in + if shouldStopObservation { + observer = nil /* deallocation right before notification */ + } + shouldStopObservation = true + return () + }) + }) + observation.scheduling = .unsafe + observer = observation.start( + in: dbWriter, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + notificationExpectation.fulfill() + }) + } + + try dbWriter.write { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + } + waitForExpectations(timeout: 0.2, handler: nil) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } } diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 866b67556..64b3124de 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -137,57 +137,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } } - func testAsyncSchedulingWithoutInitialFetch() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { - try $0.execute(sql: """ - CREATE TABLE source(name TEXT); - INSERT INTO source VALUES ('a'); - CREATE TABLE a(value INTEGER); - CREATE TABLE b(value INTEGER); - """) - } - - var results: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - var observation = ValueObservation.tracking { db -> Int in - let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! - } - observation.scheduling = .async(onQueue: DispatchQueue.main, startImmediately: false) - - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - results.append(count) - notificationExpectation.fulfill() - }) - - // Can't test observedRegion because it is defined asynchronously - - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 - try db.execute(sql: "INSERT INTO b VALUES (1)") // - - try db.execute(sql: "INSERT INTO b VALUES (1)") // - - try db.execute(sql: "UPDATE source SET name = 'b'") // 2 - try db.execute(sql: "INSERT INTO a VALUES (1)") // - - try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [1, 2, 3]) - - let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") - } - } - - func testAsyncSchedulingWithInitialFetch() throws { + func testAsyncScheduling() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: """ @@ -207,7 +157,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } - observation.scheduling = .async(onQueue: DispatchQueue.main, startImmediately: true) + observation.scheduling = .async(onQueue: DispatchQueue.main) let observer = observation.start( in: dbQueue, @@ -237,57 +187,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } } - func testUnsafeSchedulingWithoutInitialFetch() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { - try $0.execute(sql: """ - CREATE TABLE source(name TEXT); - INSERT INTO source VALUES ('a'); - CREATE TABLE a(value INTEGER); - CREATE TABLE b(value INTEGER); - """) - } - - var results: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - var observation = ValueObservation.tracking { db -> Int in - let table = try String.fetchOne(db, sql: "SELECT name FROM source")! - return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! - } - observation.scheduling = .unsafe(startImmediately: false) - - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - results.append(count) - notificationExpectation.fulfill() - }) - - // Can't test observedRegion because it is defined asynchronously - - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in - try db.execute(sql: "INSERT INTO a VALUES (1)") // 1 - try db.execute(sql: "INSERT INTO b VALUES (1)") // - - try db.execute(sql: "INSERT INTO b VALUES (1)") // - - try db.execute(sql: "UPDATE source SET name = 'b'") // 2 - try db.execute(sql: "INSERT INTO a VALUES (1)") // - - try db.execute(sql: "INSERT INTO b VALUES (1)") // 3 - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [1, 2, 3]) - - let token = observer as! ValueObserverToken> // Non-public implementation detail - XCTAssertEqual(token.observer.observedRegion.description, "b(value),source(name)") - } - } - - func testUnsafeSchedulingWithInitialFetch() throws { + func testUnsafeScheduling() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: """ @@ -307,7 +207,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } - observation.scheduling = .unsafe(startImmediately: true) + observation.scheduling = .unsafe let observer = observation.start( in: dbQueue, diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift index e299e3e82..d8b06f2a4 100644 --- a/Tests/GRDBTests/ValueObservationSchedulingTests.swift +++ b/Tests/GRDBTests/ValueObservationSchedulingTests.swift @@ -145,7 +145,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { try test(makeDatabasePool()) } - func testCustomQueueStartImmediately() throws { + func testCustomQueue() throws { func test(_ dbWriter: DatabaseWriter) throws { // We need something to change try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -162,7 +162,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }) - observation.scheduling = .async(onQueue: queue, startImmediately: true) + observation.scheduling = .async(onQueue: queue) let observer = observation.start( in: dbWriter, @@ -186,48 +186,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { try test(makeDatabasePool()) } - func testCustomQueueDontStartImmediately() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }) - observation.scheduling = .async(onQueue: queue, startImmediately: false) - - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testCustomQueueError() throws { + func testCustomQueueImmediateError() throws { func test(_ dbWriter: DatabaseWriter) throws { // We need something to change try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -246,7 +205,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { fetch: { _ in throw TestError() }, value: { $0 }) var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) - observation.scheduling = .async(onQueue: queue, startImmediately: false) + observation.scheduling = .async(onQueue: queue) let observer = observation.start( in: dbWriter, @@ -255,7 +214,52 @@ class ValueObservationSchedulingTests: GRDBTestCase { errorCount += 1 notificationExpectation.fulfill() }, - onChange: { _ in fatalError() }) + onChange: { _ in XCTFail("Unexpected value") }) + withExtendedLifetime(observer) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testCustomQueueDelayedError() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var errorCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + struct TestError: Error { } + var shouldThrow = false + let reducer = AnyValueReducer( + fetch: { _ in + if shouldThrow { + throw TestError() + } + shouldThrow = true + }, + value: { $0 }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.scheduling = .async(onQueue: queue) + + let observer = observation.start( + in: dbWriter, + onError: { error in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + errorCount += 1 + notificationExpectation.fulfill() + }, + onChange: { _ in }) try withExtendedLifetime(observer) { try dbWriter.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") @@ -270,7 +274,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { try test(makeDatabasePool()) } - func testUnsafeStartImmediatelyFromMainQueue() throws { + func testUnsafeStartFromMainQueue() throws { func test(_ dbWriter: DatabaseWriter) throws { // We need something to change try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -286,7 +290,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }) - observation.scheduling = .unsafe(startImmediately: true) + observation.scheduling = .unsafe let observer = observation.start( in: dbWriter, @@ -313,7 +317,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { try test(makeDatabasePool()) } - func testUnsafeStartImmediatelyFromCustomQueue() throws { + func testUnsafeStartFromCustomQueue() throws { func test(_ dbWriter: DatabaseWriter) throws { // We need something to change try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -330,7 +334,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }) - observation.scheduling = .unsafe(startImmediately: true) + observation.scheduling = .unsafe var observer: TransactionObserver? queue.async { observer = observation.start( @@ -359,43 +363,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { try test(makeDatabasePool()) } - func testUnsafeDontStartImmediately() throws { - func test(_ dbWriter: DatabaseWriter) throws { - // We need something to change - try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - }) - observation.scheduling = .unsafe(startImmediately: false) - - let observer = observation.start( - in: dbWriter, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbWriter.write { - try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1]) - } - } - - try test(makeDatabaseQueue()) - try test(makeDatabasePool()) - } - - func testUnsafeError() throws { + func testUnsafeImmediateError() throws { func test(_ dbWriter: DatabaseWriter) throws { // We need something to change try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -410,7 +378,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { fetch: { _ in throw TestError() }, value: { $0 }) var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) - observation.scheduling = .unsafe(startImmediately: false) + observation.scheduling = .unsafe let observer = observation.start( in: dbWriter, @@ -418,7 +386,47 @@ class ValueObservationSchedulingTests: GRDBTestCase { errorCount += 1 notificationExpectation.fulfill() }, - onChange: { _ in fatalError() }) + onChange: { _ in XCTFail("Unexpected value") }) + withExtendedLifetime(observer) { + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) + } + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testUnsafeDelayedError() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var errorCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + struct TestError: Error { } + var shouldThrow = false + let reducer = AnyValueReducer( + fetch: { _ in + if shouldThrow { + throw TestError() + } + shouldThrow = true + }, + value: { $0 }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.scheduling = .unsafe + + let observer = observation.start( + in: dbWriter, + onError: { error in + errorCount += 1 + notificationExpectation.fulfill() + }, + onChange: { _ in }) try withExtendedLifetime(observer) { try dbWriter.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES")