diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index afb8fb877..7edac397d 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -199,9 +199,6 @@ 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; 564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; 564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; - 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; - 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; - 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; 564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; }; 564CE59E21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; }; 564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */; }; @@ -457,6 +454,7 @@ 5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; }; 5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; }; 5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; }; + 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; }; 568735A21CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; }; 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; 568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; @@ -864,7 +862,6 @@ AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA482291707D00478429 /* Inflections+English.swift */; }; AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; }; AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56172947223533F40006E219 /* EncodableRecord.swift */; }; - AAA4DCAB230F1E0600C74B15 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; }; AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; @@ -1254,7 +1251,6 @@ 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; - 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = ""; }; 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; @@ -1353,6 +1349,7 @@ 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; + 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; }; 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDateComponentsTests.swift; sourceTree = ""; }; @@ -1671,7 +1668,7 @@ isa = PBXGroup; children = ( 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, - 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */, + 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */, 564CE43021AA901800652B19 /* ValueObserver.swift */, 56AACAA022ACEC9700A40F2A /* ValueReducer */, ); @@ -2767,7 +2764,6 @@ 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, - 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 563EF45D2163309F007DAACD /* Inflections.swift in Sources */, 569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */, @@ -2917,7 +2913,6 @@ 569BBA4F229170F900478429 /* Inflections+English.swift in Sources */, 5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */, 5617294F223533F40006E219 /* EncodableRecord.swift in Sources */, - 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -3463,7 +3458,6 @@ AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */, AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */, AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */, - AAA4DCAB230F1E0600C74B15 /* ValueObservation+MapReducer.swift in Sources */, AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */, AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */, AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */, @@ -3779,7 +3773,6 @@ 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, @@ -3789,6 +3782,7 @@ 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, + 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */, 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 8fc4c63e6..630aa9887 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -775,14 +775,23 @@ extension DatabasePool: DatabaseReader { public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - add( + // DatabasePool supports concurrent reads and can accelerate the + // notification of the initial value by not waiting for an access + // to the writer queue, which may be busy executing a + // long-runnning transaction. + // + // Obviously this only works if observation does need a write access. + let concurrentInitialValue = !observation.requiresWriteAccess + + return add( observation: observation, - // DatabasePool supports concurrent reads - prependingConcurrentFetch: !observation.requiresWriteAccess, + scheduler: scheduler, + concurrentInitialValue: concurrentInitialValue, onError: onError, onChange: onChange) } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index f29007fec..8421d9f4b 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -451,14 +451,16 @@ extension DatabaseQueue { public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { add( observation: observation, + scheduler: scheduler, // DatabaseQueue does not support concurrent reads - prependingConcurrentFetch: false, + concurrentInitialValue: false, onError: onError, onChange: onChange) } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index c23c3f6d7..8a6c7fee9 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -254,6 +254,7 @@ public protocol DatabaseReader: AnyObject { /// - returns: a TransactionObserver func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver @@ -300,22 +301,21 @@ extension DatabaseReader { func addReadOnly( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - switch observation._scheduling { - case .fetchWhenStarted: - GRDBPrecondition(DispatchQueue.isMain, "ValueObservation must be started from the main Dispatch queue.") + if scheduler.impl.fetchOnStart() { do { try onChange(unsafeReentrantRead(observation.fetchValue)) } catch { onError(error) } - case let .async(onDispatchQueue: queue): + } else { asyncRead { dbResult in let result = dbResult.tryMap(observation.fetchValue) - queue.async { + scheduler.impl.schedule { do { try onChange(result.get()) } catch { @@ -414,11 +414,12 @@ public final class AnyDatabaseReader: DatabaseReader { /// :nodoc: public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - return base.add(observation: observation, onError: onError, onChange: onChange) + return base.add(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) } /// :nodoc: diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 8d7dbc14e..642a1b8d6 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -118,11 +118,12 @@ extension DatabaseSnapshot { public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - return addReadOnly(observation: observation, onError: onError, onChange: onChange) + return addReadOnly(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) } public func remove(transactionObserver: TransactionObserver) { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index f1ae684de..11a78d5ea 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -304,27 +304,30 @@ extension DatabaseWriter { func add( observation: ValueObservation, - prependingConcurrentFetch: Bool, + scheduler: ValueObservationScheduler, + concurrentInitialValue: Bool, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { if configuration.readonly { - return addReadOnly(observation: observation, onError: onError, onChange: onChange) + return addReadOnly( + observation: observation, + scheduler: scheduler, + onError: onError, + onChange: onChange) } - + let observer = ValueObserver( requiresWriteAccess: observation.requiresWriteAccess, writer: self, reducer: observation.makeReducer(), - notificationQueue: observation._scheduling.notificationQueue, + scheduler: scheduler, reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"), onError: onError, onChange: onChange) - switch observation._scheduling { - case .fetchWhenStarted: - GRDBPrecondition(Thread.isMainThread, "ValueObservation must be started from the main thread.") + if scheduler.impl.fetchOnStart() { do { let initialValue: Reducer.Value = try unsafeReentrantWrite { db in // Fetch an initial value and start observation @@ -336,9 +339,8 @@ extension DatabaseWriter { } catch { onError(error) } - - case .async: - if prependingConcurrentFetch { + } else { + if concurrentInitialValue { // Fetch an initial value without waiting for the writer. asyncRead { dbResult in do { @@ -357,7 +359,7 @@ extension DatabaseWriter { observer.send(value) } - // Now we can start observations + // Now we can start observation db.add(transactionObserver: observer, extent: .observerLifetime) } catch { observer.send(error) @@ -553,10 +555,11 @@ public final class AnyDatabaseWriter: DatabaseWriter { /// :nodoc: public func add( observation: ValueObservation, + scheduler: ValueObservationScheduler, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - base.add(observation: observation, onError: onError, onChange: onChange) + base.add(observation: observation, scheduler: scheduler, onError: onError, onChange: onChange) } } diff --git a/GRDB/ValueObservation/ValueObservation+MapReducer.swift b/GRDB/ValueObservation/ValueObservation+MapReducer.swift deleted file mode 100644 index 11994c695..000000000 --- a/GRDB/ValueObservation/ValueObservation+MapReducer.swift +++ /dev/null @@ -1,10 +0,0 @@ -extension ValueObservation { - /// Returns a ValueObservation with a transformed reducer. - func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { - let makeReducer = self.makeReducer - return ValueObservation( - makeReducer: { transform(makeReducer()) }, - _scheduling: _scheduling, - requiresWriteAccess: requiresWriteAccess) - } -} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 64feb7d91..d451a1aa0 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -29,7 +29,10 @@ enum ValueObservationScheduling { /// /// For example: /// -/// let observation = ValueObservation.tracking(Player.fetchAll) +/// let observation = ValueObservation.tracking { db in +/// try Player.fetchAll(db) +/// } +/// /// let observer = try observation.start( /// in: dbQueue, /// onError: { error in ... }, @@ -38,13 +41,9 @@ enum ValueObservationScheduling { /// }) public struct ValueObservation { /// The reducer is created when observation starts, and is triggered upon - /// each database change in *observedRegion*. + /// each database change. var makeReducer: () -> Reducer - /// `scheduling` controls how fresh values are notified. Default - /// is `ValueObservationScheduling.async(onDispatchQueue: .main)`. - var _scheduling = ValueObservationScheduling.async(onDispatchQueue: .main) - /// Default is false. Set this property to true when the observation /// requires write access in order to fetch fresh values. Fetches are then /// wrapped inside a savepoint. @@ -52,37 +51,30 @@ public struct ValueObservation { /// Don't set this flag to true unless you really need it. A read/write /// observation is less efficient than a read-only observation. public var requiresWriteAccess: Bool = false + + /// Returns a ValueObservation with a transformed reducer. + func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { + let makeReducer = self.makeReducer + return ValueObservation( + makeReducer: { transform(makeReducer()) }, + requiresWriteAccess: requiresWriteAccess) + } } -extension ValueObservation: KeyPathRefining { +extension ValueObservation { - // MARK: - Scheduling + // MARK: - Starting Observation - /// Returns a ValueObservation which notifies fresh values on the given - /// dispatch queue, asynchronously. + /// Starts the value observation in the provided database reader (such as + /// a database queue or database pool), and returns a transaction observer. + /// + /// The observation lasts until the returned observer is deallocated. /// /// For example: /// - /// let observation = ValueObservation - /// .tracking(Player.fetchAll) - /// .notify(onDispatchQueue: .main) - /// - /// Note that by default, ValueObservation notifies fresh values on the main - /// dispatch queue, asynchronously. - public func notify(onDispatchQueue queue: DispatchQueue) -> Self { - with(\._scheduling, .async(onDispatchQueue: queue)) - } - - /// Returns a ValueObservation which notifies fresh values on the main - /// dispatch queue. The initial value is notified immediately when the - /// `start()` method is called. Subsequent values are - /// notified asynchronously. - /// - /// For example: - /// - /// let observation = ValueObservation - /// .tracking(Player.fetchAll) - /// .fetchWhenStarted() + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } /// /// let observer = try observation.start( /// in: dbQueue, @@ -90,30 +82,36 @@ extension ValueObservation: KeyPathRefining { /// onChange: { players: [Player] in /// print("fresh players: \(players)") /// }) + /// + /// By default, fresh values are dispatched asynchronously on the + /// main queue. You can change this behavior by providing a scheduler. + /// For example, `.immediate` notifies all values on the main queue as well, + /// but the first one is immediately notified when the start() method + /// is called: + /// + /// let observer = try observation.start( + /// in: dbQueue, + /// scheduler: .immediate, // <- + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("fresh players: \(players)") + /// }) /// // <- here "fresh players" is already printed. /// - /// - important: Such an observation must be started from the main thread. - /// A fatal error is raised otherwise. - public func fetchWhenStarted() -> Self { - with(\._scheduling, .fetchWhenStarted) - } - - // MARK: - Starting Observation - - /// Starts the value observation in the provided database reader (such as - /// a database queue or database pool), and returns a transaction observer. - /// /// - parameter reader: A DatabaseReader. + /// - parameter scheduler: A Scheduler. By default, fresh values are + /// dispatched asynchronously on the main queue. /// - parameter onError: A closure that is provided eventual errors that - /// happen during observation + /// happen during observation /// - parameter onChange: A closure that is provided fresh values /// - returns: a TransactionObserver public func start( in reader: DatabaseReader, + scheduler: ValueObservationScheduler = .async(onQueue: .main), onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) -> TransactionObserver { - return reader.add(observation: self, onError: onError, onChange: onChange) + return reader.add(observation: self, scheduler: scheduler, onError: onError, onChange: onChange) } // MARK: - Fetching Values diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift new file mode 100644 index 000000000..2037f2b23 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -0,0 +1,81 @@ +import Dispatch + +/// ValueObservationScheduler determines how ValueObservation notifies its +/// fresh values. +public class ValueObservationScheduler { + let impl: ValueObservationSchedulerImpl + + init(impl: ValueObservationSchedulerImpl) { + self.impl = impl + } + + /// A scheduler which asynchronously notifies fresh value of the + /// given DispatchQueue. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let observer = try observation.start( + /// in: dbQueue, + /// scheduler: .async(onQueue: .main), + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("fresh players: \(players)") + /// }) + public static func async(onQueue queue: DispatchQueue) -> ValueObservationScheduler { + return ValueObservationScheduler(impl: queue) + } + + /// A scheduler which notifies all values on the main queue. The first one + /// is immediately notified when the start() method is called. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let observer = try observation.start( + /// in: dbQueue, + /// scheduler: .immediate, + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("fresh players: \(players)") + /// }) + /// // <- here "fresh players" is already printed. + /// + /// - important: this scheduler requires that the observation is started + /// from the main queue. A fatal error is raised otherwise. + public static let immediate = ValueObservationScheduler(impl: ImmediateImpl()) +} + +protocol ValueObservationSchedulerImpl { + func schedule(_ action: @escaping () -> Void) + func fetchOnStart() -> Bool +} + +struct ImmediateImpl: ValueObservationSchedulerImpl { + func schedule(_ action: @escaping () -> Void) { + DispatchQueue.main.async(execute: action) + } + + func fetchOnStart() -> Bool { + GRDBPrecondition( + DispatchQueue.isMain, + "ValueObservation must be started from the main Dispatch queue.") + return true + } +} + +extension DispatchQueue: ValueObservationSchedulerImpl { + func schedule(_ action: @escaping () -> Void) { + async(execute: action) + } + + func fetchOnStart() -> Bool { + false + } +} diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index a31d7404d..38d57166b 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -8,7 +8,7 @@ final class ValueObserver { private var reducer: Reducer private let requiresWriteAccess: Bool private weak var writer: DatabaseWriter? - private let notificationQueue: DispatchQueue? + private let scheduler: ValueObservationScheduler private let reduceQueue: DispatchQueue private let onError: (Error) -> Void private let onChange: (Reducer.Value) -> Void @@ -18,7 +18,7 @@ final class ValueObserver { requiresWriteAccess: Bool, writer: DatabaseWriter, reducer: Reducer, - notificationQueue: DispatchQueue?, + scheduler: ValueObservationScheduler, reduceQueue: DispatchQueue, onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void) @@ -26,7 +26,7 @@ final class ValueObserver { self.writer = writer self.reducer = reducer self.requiresWriteAccess = requiresWriteAccess - self.notificationQueue = notificationQueue + self.scheduler = scheduler self.reduceQueue = reduceQueue self.onError = onError self.onChange = onChange @@ -58,27 +58,17 @@ extension ValueObserver { func send(_ value: Reducer.Value) { if isCancelled { return } - if let queue = notificationQueue { - let onChange = self.onChange - queue.async { - if self.isCancelled { return } - onChange(value) - } - } else { - onChange(value) + scheduler.impl.schedule { + if self.isCancelled { return } + self.onChange(value) } } func send(_ error: Error) { if isCancelled { return } - if let queue = notificationQueue { - let onError = self.onError - queue.async { - if self.isCancelled { return } - onError(error) - } - } else { - onError(error) + scheduler.impl.schedule { + if self.isCancelled { return } + self.onError(error) } } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 3c20bc305..c42669f08 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -73,6 +73,8 @@ 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */; }; + 563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */; }; 563B06D12185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */; }; 563B06D22185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */; }; 563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */; }; @@ -113,8 +115,6 @@ 564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; }; 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; - 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; - 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; 564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; }; @@ -773,6 +773,7 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; + 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = ""; }; 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = ""; }; @@ -794,7 +795,6 @@ 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; 564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; - 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; @@ -1186,7 +1186,7 @@ isa = PBXGroup; children = ( 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, - 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */, + 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */, 564CE43B21AA955B00652B19 /* ValueObserver.swift */, 56C0538822ACEECD0029D27D /* ValueReducer */, ); @@ -2173,7 +2173,6 @@ 566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA800D1CFB2871003DC1BA /* DatabasePool.swift in Sources */, 5656A87C2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */, F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */, @@ -2188,6 +2187,7 @@ 5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */, 56C0539A22ACEECD0029D27D /* Combine.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, + 563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, 5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5656A88A2295BD56001FF3FF /* SQLExpressible.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, @@ -2510,7 +2510,6 @@ 566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA80691CFB2E55003DC1BA /* DatabasePool.swift in Sources */, 5656A87B2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */, F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */, @@ -2525,6 +2524,7 @@ 5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */, 56C0539922ACEECD0029D27D /* Combine.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, + 563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, 5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5656A8892295BD56001FF3FF /* SQLExpressible.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, diff --git a/Tests/GRDBTests/ValueObservationCombineTests.swift b/Tests/GRDBTests/ValueObservationCombineTests.swift index 0d1f13d11..4a62de833 100644 --- a/Tests/GRDBTests/ValueObservationCombineTests.swift +++ b/Tests/GRDBTests/ValueObservationCombineTests.swift @@ -658,14 +658,13 @@ class ValueObservationCombineTests: GRDBTestCase { func testHeterogeneusCombine2() throws { struct V1 { } struct V2 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation = ValueObservation - .combine(observation1, observation2) - .fetchWhenStarted() + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }) var value: (V1, V2)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -675,15 +674,14 @@ class ValueObservationCombineTests: GRDBTestCase { struct V1 { } struct V2 { } struct V3 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation = ValueObservation - .combine(observation1, observation2, observation3) - .fetchWhenStarted() + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }) var value: (V1, V2, V3)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -694,16 +692,15 @@ class ValueObservationCombineTests: GRDBTestCase { struct V2 { } struct V3 { } struct V4 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation = ValueObservation - .combine(observation1, observation2, observation3, observation4) - .fetchWhenStarted() + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }) var value: (V1, V2, V3, V4)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -715,17 +712,16 @@ class ValueObservationCombineTests: GRDBTestCase { struct V3 { } struct V4 { } struct V5 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation5 = ValueObservation.tracking { _ in V5() } - let observation = ValueObservation - .combine(observation1, observation2, observation3, observation4, observation5) - .fetchWhenStarted() + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }, + ValueObservation.tracking { _ in V5() }) var value: (V1, V2, V3, V4, V5)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -738,18 +734,17 @@ class ValueObservationCombineTests: GRDBTestCase { struct V4 { } struct V5 { } struct V6 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation5 = ValueObservation.tracking { _ in V5() } - let observation6 = ValueObservation.tracking { _ in V6() } - let observation = ValueObservation - .combine(observation1, observation2, observation3, observation4, observation5, observation6) - .fetchWhenStarted() + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }, + ValueObservation.tracking { _ in V5() }, + ValueObservation.tracking { _ in V6() }) var value: (V1, V2, V3, V4, V5, V6)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -763,19 +758,18 @@ class ValueObservationCombineTests: GRDBTestCase { struct V5 { } struct V6 { } struct V7 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation5 = ValueObservation.tracking { _ in V5() } - let observation6 = ValueObservation.tracking { _ in V6() } - let observation7 = ValueObservation.tracking { _ in V7() } - let observation = ValueObservation - .combine(observation1, observation2, observation3, observation4, observation5, observation6, observation7) - .fetchWhenStarted() + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }, + ValueObservation.tracking { _ in V5() }, + ValueObservation.tracking { _ in V6() }, + ValueObservation.tracking { _ in V7() }) var value: (V1, V2, V3, V4, V5, V6, V7)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -790,20 +784,19 @@ class ValueObservationCombineTests: GRDBTestCase { struct V6 { } struct V7 { } struct V8 { } - let observation1 = ValueObservation.tracking { _ in V1() } - let observation2 = ValueObservation.tracking { _ in V2() } - let observation3 = ValueObservation.tracking { _ in V3() } - let observation4 = ValueObservation.tracking { _ in V4() } - let observation5 = ValueObservation.tracking { _ in V5() } - let observation6 = ValueObservation.tracking { _ in V6() } - let observation7 = ValueObservation.tracking { _ in V7() } - let observation8 = ValueObservation.tracking { _ in V8() } - let observation = ValueObservation - .combine(observation1, observation2, observation3, observation4, observation5, observation6, observation7, observation8) - .fetchWhenStarted() + let observation = ValueObservation.combine( + ValueObservation.tracking { _ in V1() }, + ValueObservation.tracking { _ in V2() }, + ValueObservation.tracking { _ in V3() }, + ValueObservation.tracking { _ in V4() }, + ValueObservation.tracking { _ in V5() }, + ValueObservation.tracking { _ in V6() }, + ValueObservation.tracking { _ in V7() }, + ValueObservation.tracking { _ in V8() }) var value: (V1, V2, V3, V4, V5, V6, V7, V8)? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -815,12 +808,11 @@ class ValueObservationCombineTests: GRDBTestCase { struct Combined { } let observation1 = ValueObservation.tracking { _ in V1() } let observation2 = ValueObservation.tracking { _ in V2() } - let observation = observation1 - .combine(observation2) { (v1: V1, v2: V2) -> Combined in Combined() } - .fetchWhenStarted() + let observation = observation1.combine(observation2) { (v1: V1, v2: V2) -> Combined in Combined() } var value: Combined? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -834,12 +826,11 @@ class ValueObservationCombineTests: GRDBTestCase { let observation1 = ValueObservation.tracking { _ in V1() } let observation2 = ValueObservation.tracking { _ in V2() } let observation3 = ValueObservation.tracking { _ in V3() } - let observation = observation1 - .combine(observation2, observation3) { (v1: V1, v2: V2, v3: V3) -> Combined in Combined() } - .fetchWhenStarted() + let observation = observation1.combine(observation2, observation3) { (v1: V1, v2: V2, v3: V3) -> Combined in Combined() } var value: Combined? _ = try observation.start( in: makeDatabaseQueue(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -855,12 +846,11 @@ class ValueObservationCombineTests: GRDBTestCase { let observation2 = ValueObservation.tracking { _ in V2() } let observation3 = ValueObservation.tracking { _ in V3() } let observation4 = ValueObservation.tracking { _ in V4() } - let observation = observation1 - .combine(observation2, observation3, observation4) { (v1: V1, v2: V2, v3: V3, v4: V4) -> Combined in Combined() } - .fetchWhenStarted() + 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(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) @@ -878,12 +868,11 @@ class ValueObservationCombineTests: GRDBTestCase { let observation3 = ValueObservation.tracking { _ in V3() } let observation4 = ValueObservation.tracking { _ in V4() } let observation5 = ValueObservation.tracking { _ in V5() } - let observation = observation1 - .combine(observation2, observation3, observation4, observation5) { (v1: V1, v2: V2, v3: V3, v4: V4, v5: V5) -> Combined in Combined() } - .fetchWhenStarted() + 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(), + scheduler: .immediate, // So that we can test the fresh value synchronously onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { value = $0 }) XCTAssertNotNil(value) diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index b880d6655..11b853ed9 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -284,9 +284,10 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { // Test that view v is not included in the observed region. // This optimization helps observation of views that feed from a // single table. - let observation = ValueObservation.tracking(request.fetchAll).fetchWhenStarted() + let observation = ValueObservation.tracking(request.fetchAll) let observer = observation.start( in: dbQueue, + scheduler: .immediate, // So that we can test the observedRegion onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { names in results.append(names) diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift index 352d826c0..ffd91ca35 100644 --- a/Tests/GRDBTests/ValueObservationMapTests.swift +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -13,9 +13,7 @@ import XCTest class ValueObservationMapTests: GRDBTestCase { func testMap() throws { let valueObservation = ValueObservation - .tracking { - try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! - } + .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } .map { "\($0)" } try assertValueObservation( @@ -31,19 +29,10 @@ class ValueObservationMapTests: GRDBTestCase { } func testMapPreservesConfiguration() { - let queue = DispatchQueue(label: "test") - var observation = ValueObservation - .tracking { _ in } - .notify(onDispatchQueue: queue) + var observation = ValueObservation.tracking { _ in } observation.requiresWriteAccess = true let mappedObservation = observation.map { _ in } XCTAssertEqual(mappedObservation.requiresWriteAccess, observation.requiresWriteAccess) - switch mappedObservation._scheduling { - case let .async(onDispatchQueue: q): - XCTAssert(q === queue) - default: - XCTFail() - } } } diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 0c3adf7c9..7724e2883 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -195,10 +195,15 @@ extension ValueObservationRecorder { // MARK: - ValueObservation + ValueObservationRecorder extension ValueObservation { - public func record(in reader: DatabaseReader) -> ValueObservationRecorder { + public func record( + in reader: DatabaseReader, + scheduler: ValueObservationScheduler = .async(onQueue: .main)) + -> ValueObservationRecorder + { let recorder = ValueObservationRecorder() let observer = start( in: reader, + scheduler: scheduler, onError: recorder.onError, onChange: recorder.onChange) recorder.receive(observer) @@ -334,7 +339,7 @@ extension XCTestCase { extension GRDBTestCase { func assertValueObservation( - _ valueObservation: ValueObservation, + _ observation: ValueObservation, records expectedValues: [Reducer.Value], setup: (Database) throws -> Void, recordedUpdates: (Database) throws -> Void, @@ -343,18 +348,26 @@ extension GRDBTestCase { throws where Reducer.Value: Equatable { - func testRecordingEqual(writer: DatabaseWriter, observation: ValueObservation) throws { + func testRecordingEqual( + writer: DatabaseWriter, + observation: ValueObservation, + scheduler: ValueObservationScheduler) throws + { try writer.write(setup) - let recorder = observation.record(in: writer) + let recorder = observation.record(in: writer, scheduler: scheduler) try writer.writeWithoutTransaction(recordedUpdates) let expectation = recorder.next(expectedValues.count) let values = try wait(for: expectation, timeout: 0.3) XCTAssertEqual(values, expectedValues, file: file, line: line) } - func testRecordingMatch(writer: DatabaseWriter, observation: ValueObservation) throws { + func testRecordingMatch( + writer: DatabaseWriter, + observation: ValueObservation, + scheduler: ValueObservationScheduler) throws + { try writer.write(setup) - let recorder = observation.record(in: writer) + let recorder = observation.record(in: writer, scheduler: scheduler) try writer.writeWithoutTransaction(recordedUpdates) let expectation = recorder .prefix(expectedValues.count + 2 /* pool may perform double initial fetch */) @@ -367,36 +380,40 @@ extension GRDBTestCase { } do { - let observation = valueObservation.fetchWhenStarted() - try testRecordingEqual(writer: DatabaseQueue(), observation: observation) - try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation) - try testRecordingEqual(writer: makeDatabasePool(), observation: observation) + let scheduler = ValueObservationScheduler.immediate + try testRecordingEqual(writer: DatabaseQueue(), observation: observation, scheduler: scheduler) + try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation, scheduler: scheduler) + try testRecordingEqual(writer: makeDatabasePool(), observation: observation, scheduler: scheduler) } do { - let observation = valueObservation.notify(onDispatchQueue: .main) - try testRecordingEqual(writer: DatabaseQueue(), observation: observation) - try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation) - if valueObservation.requiresWriteAccess || !valueObservation.makeReducer().isObservedRegionDeterministic { - try testRecordingEqual(writer: makeDatabasePool(), observation: observation) + let scheduler = ValueObservationScheduler.async(onQueue: .main) + try testRecordingEqual(writer: DatabaseQueue(), observation: observation, scheduler: scheduler) + try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation, scheduler: scheduler) + if observation.requiresWriteAccess || !observation.makeReducer().isObservedRegionDeterministic { + try testRecordingEqual(writer: makeDatabasePool(), observation: observation, scheduler: scheduler) } else { // DatabasePool performs an immediate async fetch and may miss initial changes - try testRecordingMatch(writer: makeDatabasePool(), observation: observation) + try testRecordingMatch(writer: makeDatabasePool(), observation: observation, scheduler: scheduler) } } } func assertValueObservation( - _ valueObservation: ValueObservation, + _ observation: ValueObservation, fails testFailure: (Failure, DatabaseWriter) throws -> Void, setup: (Database) throws -> Void, file: StaticString = #file, line: UInt = #line) throws { - func test(writer: DatabaseWriter, observation: ValueObservation) throws { + func test( + writer: DatabaseWriter, + observation: ValueObservation, + scheduler: ValueObservationScheduler) throws + { try writer.write(setup) - let recorder = observation.record(in: writer) + let recorder = observation.record(in: writer, scheduler: scheduler) let (_, error) = try wait(for: recorder.failure(), timeout: 0.3) if let error = error as? Failure { try testFailure(error, writer) @@ -406,17 +423,17 @@ extension GRDBTestCase { } do { - let observation = valueObservation.fetchWhenStarted() - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) + let scheduler = ValueObservationScheduler.immediate + try test(writer: DatabaseQueue(), observation: observation, scheduler: scheduler) + try test(writer: makeDatabaseQueue(), observation: observation, scheduler: scheduler) + try test(writer: makeDatabasePool(), observation: observation, scheduler: scheduler) } do { - let observation = valueObservation.notify(onDispatchQueue: .main) - try test(writer: DatabaseQueue(), observation: observation) - try test(writer: makeDatabaseQueue(), observation: observation) - try test(writer: makeDatabasePool(), observation: observation) + let scheduler = ValueObservationScheduler.async(onQueue: .main) + try test(writer: DatabaseQueue(), observation: observation, scheduler: scheduler) + try test(writer: makeDatabaseQueue(), observation: observation, scheduler: scheduler) + try test(writer: makeDatabasePool(), observation: observation, scheduler: scheduler) } } } diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index 3781fb75b..bf6697d69 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -44,11 +44,12 @@ class ValueObservationReducerTests: GRDBTestCase { }) // Create an observation - let observation = ValueObservation(makeReducer: { reducer }).fetchWhenStarted() + let observation = ValueObservation(makeReducer: { reducer }) // Start observation let observer = observation.start( in: dbWriter, + scheduler: .immediate, onError: { errors.append($0) notificationExpectation.fulfill() @@ -114,14 +115,13 @@ class ValueObservationReducerTests: GRDBTestCase { func test(_ dbWriter: DatabaseWriter) throws { // Create an observation struct TestError: Error { } - let observation = ValueObservation - .tracking { _ in throw TestError() } - .fetchWhenStarted() + let observation = ValueObservation.tracking { _ in throw TestError() } // Start observation var error: TestError? _ = observation.start( in: dbWriter, + scheduler: .immediate, onError: { error = $0 as? TestError }, onChange: { _ in }) XCTAssertNotNil(error) @@ -204,9 +204,10 @@ class ValueObservationReducerTests: GRDBTestCase { shouldStopObservation = true }, value: { _ in () }) - }).fetchWhenStarted() + }) observer = observation.start( in: dbWriter, + scheduler: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { _ in notificationExpectation.fulfill() @@ -246,9 +247,10 @@ class ValueObservationReducerTests: GRDBTestCase { shouldStopObservation = true return () }) - }).fetchWhenStarted() + }) observer = observation.start( in: dbWriter, + scheduler: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { _ in notificationExpectation.fulfill() diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index f0f003f70..08dd70b75 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -123,7 +123,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { onChange: { (int: Int, string: String) in }) // <- destructure } - func testVaryingRegionTrackingMainQueueScheduling() throws { + func testVaryingRegionTrackingImmediateScheduling() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute(sql: """ @@ -139,15 +139,14 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - let observation = ValueObservation - .trackingVaryingRegion({ 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)")! - }) - .fetchWhenStarted() + let observation = ValueObservation.trackingVaryingRegion({ 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)")! + }) let observer = observation.start( in: dbQueue, + scheduler: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in results.append(count) @@ -191,15 +190,14 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - let observation = ValueObservation - .trackingVaryingRegion({ 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)")! - }) - .notify(onDispatchQueue: .main) + let observation = ValueObservation.trackingVaryingRegion({ 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)")! + }) let observer = observation.start( in: dbQueue, + scheduler: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in results.append(count) diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift index 29b2a0bce..1178748c5 100644 --- a/Tests/GRDBTests/ValueObservationSchedulingTests.swift +++ b/Tests/GRDBTests/ValueObservationSchedulingTests.swift @@ -11,7 +11,7 @@ import XCTest #endif class ValueObservationSchedulingTests: GRDBTestCase { - func testImmediateObservationStartedFromMainQueue() throws { + func testImmediateScheduling() 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)") } @@ -24,11 +24,10 @@ class ValueObservationSchedulingTests: GRDBTestCase { let key = DispatchSpecificKey<()>() DispatchQueue.main.setSpecific(key: key, value: ()) - let observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } - .fetchWhenStarted() + let observation = ValueObservation.tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } let observer = observation.start( in: dbWriter, + scheduler: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) @@ -53,7 +52,7 @@ class ValueObservationSchedulingTests: GRDBTestCase { try test(makeDatabasePool()) } - func testImmeediateError() throws { + func testImmediateError() 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)") } @@ -67,18 +66,17 @@ class ValueObservationSchedulingTests: GRDBTestCase { DispatchQueue.main.setSpecific(key: key, value: ()) var nextError: Error? = nil // If not null, observation throws an error - let observation = ValueObservation - .tracking({ db in - _ = try Int.fetchOne(db, sql: "SELECT * FROM t") - if let error = nextError { - nextError = nil - throw error - } - }) - .fetchWhenStarted() + let observation = ValueObservation.tracking({ db in + _ = try Int.fetchOne(db, sql: "SELECT * FROM t") + if let error = nextError { + nextError = nil + throw error + } + }) let observer = observation.start( in: dbWriter, + scheduler: .immediate, onError: { error in XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) errorCount += 1 @@ -118,12 +116,11 @@ class ValueObservationSchedulingTests: GRDBTestCase { let key = DispatchSpecificKey<()>() queue.setSpecific(key: key, value: ()) - let observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } - .notify(onDispatchQueue: queue) + let observation = ValueObservation.tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } let observer = observation.start( in: dbWriter, + scheduler: .async(onQueue: queue), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) @@ -159,12 +156,11 @@ class ValueObservationSchedulingTests: GRDBTestCase { queue.setSpecific(key: key, value: ()) struct TestError: Error { } - let observation = ValueObservation - .tracking { _ in throw TestError() } - .notify(onDispatchQueue: queue) + let observation = ValueObservation.tracking { _ in throw TestError() } let observer = observation.start( in: dbWriter, + scheduler: .async(onQueue: queue), onError: { error in XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) errorCount += 1 @@ -197,18 +193,17 @@ class ValueObservationSchedulingTests: GRDBTestCase { struct TestError: Error { } var shouldThrow = false - let observation = ValueObservation - .tracking({ db in - _ = try Int.fetchOne(db, sql: "SELECT * FROM t") - if shouldThrow { - throw TestError() - } - shouldThrow = true - }) - .notify(onDispatchQueue: queue) + let observation = ValueObservation.tracking({ db in + _ = try Int.fetchOne(db, sql: "SELECT * FROM t") + if shouldThrow { + throw TestError() + } + shouldThrow = true + }) let observer = observation.start( in: dbWriter, + scheduler: .async(onQueue: queue), onError: { error in XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) errorCount += 1