mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-24 04:07:47 +00:00
ValueObservation.handleEvents
This commit is contained in:
1 parent
276c6a4acf
commit
dd76cdffec
13 files changed
+281
-140
No files matched your search
@@ -166,6 +166,10 @@
|
||||
563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; };
|
||||
563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
|
||||
563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
|
||||
563B8F92249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
|
||||
563B8F93249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
|
||||
563B8F94249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
|
||||
563B8F95249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
|
||||
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
|
||||
@@ -1245,6 +1249,7 @@
|
||||
563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
|
||||
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
|
||||
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
|
||||
563B8F91249E6171007A48C9 /* Trace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = "<group>"; };
|
||||
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
|
||||
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
|
||||
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
|
||||
@@ -2209,6 +2214,7 @@
|
||||
56AACAA722ACED7100A40F2A /* Fetch.swift */,
|
||||
5613ED3421A95A5C00DC7A68 /* Map.swift */,
|
||||
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */,
|
||||
563B8F91249E6171007A48C9 /* Trace.swift */,
|
||||
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */,
|
||||
);
|
||||
path = ValueReducer;
|
||||
@@ -2809,6 +2815,7 @@
|
||||
5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
563B8F94249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
568D13212207213F00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */,
|
||||
5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
@@ -2976,6 +2983,7 @@
|
||||
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
|
||||
@@ -3522,6 +3530,7 @@
|
||||
AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */,
|
||||
AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */,
|
||||
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */,
|
||||
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
|
||||
AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */,
|
||||
@@ -3860,6 +3869,7 @@
|
||||
5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
5653EB0620944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
563B8F92249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
|
||||
@@ -808,33 +808,19 @@ extension DatabasePool: DatabaseReader {
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
return _addReadOnly(observation: observation, scheduling: scheduler)
|
||||
}
|
||||
|
||||
if observation.requiresWriteAccess {
|
||||
let observer = _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
let observer = _addWriteOnly( observation: observation, scheduling: scheduler)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
let observer = _addConcurrent(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
let observer = _addConcurrent( observation: observation, scheduling: scheduler)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
|
||||
@@ -842,9 +828,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// the writer.
|
||||
private func _addConcurrent<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
@@ -853,14 +837,11 @@ extension DatabasePool: DatabaseReader {
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver<Reducer>(
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
let observer = ValueObserver(
|
||||
observation: observation,
|
||||
writer: self,
|
||||
reducer: observation.makeReducer(),
|
||||
scheduling: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel))
|
||||
|
||||
// Starting a concurrent observation means that we'll fetch the initial
|
||||
// value right away, without waiting for an access to the writer queue,
|
||||
@@ -901,11 +882,11 @@ extension DatabasePool: DatabaseReader {
|
||||
do {
|
||||
let initialSnapshot = try makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
observation.events.onValue?(initialValue)
|
||||
add(observer: observer, from: initialSnapshot)
|
||||
} catch {
|
||||
observer.cancel()
|
||||
onError(error)
|
||||
observer.complete()
|
||||
observation.events.onError?(error)
|
||||
}
|
||||
} else {
|
||||
let label = configuration.identifier(
|
||||
@@ -963,8 +944,11 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
if fetchNeeded, let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
if fetchNeeded {
|
||||
observer.events.onDatabaseChange?()
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
|
||||
@@ -475,24 +475,14 @@ extension DatabaseQueue {
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
return _addReadOnly(observation: observation, scheduling: scheduler)
|
||||
}
|
||||
|
||||
let observer = _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
let observer = _addWriteOnly(observation: observation, scheduling: scheduler)
|
||||
return AnyDatabaseCancellable(cancel: observer.cancel)
|
||||
}
|
||||
}
|
||||
@@ -246,17 +246,12 @@ public protocol DatabaseReader: AnyObject {
|
||||
/// method instead.
|
||||
///
|
||||
/// - parameter observation: the stared observation
|
||||
/// - parameter onError: a closure that is provided by eventual errors that happen
|
||||
/// during observation
|
||||
/// - parameter onChange: a closure that is provided fresh values
|
||||
/// - returns: a TransactionObserver
|
||||
///
|
||||
/// :nodoc:
|
||||
func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> DatabaseCancellable
|
||||
}
|
||||
|
||||
@@ -300,16 +295,15 @@ extension DatabaseReader {
|
||||
/// initial value.
|
||||
func _addReadOnly<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
try onChange(unsafeReentrantRead(observation.fetchValue))
|
||||
let value = try unsafeReentrantRead(observation.fetchValue)
|
||||
observation.events.onValue?(value)
|
||||
} catch {
|
||||
onError(error)
|
||||
observation.events.onError?(error)
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
} else {
|
||||
@@ -327,9 +321,9 @@ extension DatabaseReader {
|
||||
scheduler.schedule {
|
||||
guard !isCancelled else { return }
|
||||
do {
|
||||
try onChange(result.get())
|
||||
try observation.events.onValue?(result.get())
|
||||
} catch {
|
||||
onError(error)
|
||||
observation.events.onError?(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -418,15 +412,9 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
base._add(observation: observation, scheduling: scheduler)
|
||||
}
|
||||
}
|
||||
@@ -131,15 +131,9 @@ extension DatabaseSnapshot {
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
_addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
_addReadOnly(observation: observation, scheduling: scheduler)
|
||||
}
|
||||
}
|
||||
@@ -311,9 +311,7 @@ extension DatabaseWriter {
|
||||
/// A write-only observation only uses the serialized writer
|
||||
func _addWriteOnly<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> ValueObserver<Reducer> // For testability
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
@@ -321,14 +319,11 @@ extension DatabaseWriter {
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver<Reducer>(
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
let observer = ValueObserver(
|
||||
observation: observation,
|
||||
writer: self,
|
||||
reducer: observation.makeReducer(),
|
||||
scheduling: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
scheduler: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel))
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
@@ -337,10 +332,10 @@ extension DatabaseWriter {
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
return initialValue
|
||||
}
|
||||
onChange(initialValue)
|
||||
observation.events.onValue?(initialValue)
|
||||
} catch {
|
||||
observer.cancel()
|
||||
onError(error)
|
||||
observer.complete()
|
||||
observation.events.onError?(error)
|
||||
}
|
||||
} else {
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
@@ -529,15 +524,9 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: _ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
base._add(observation: observation, scheduling: scheduler)
|
||||
}
|
||||
}
|
||||
@@ -134,3 +134,39 @@ func throwingFirstError<T>(execute: () throws -> T, finally: () throws -> Void)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
|
||||
struct PrintOutputStream: TextOutputStream {
|
||||
func write(_ string: String) {
|
||||
Swift.print(string)
|
||||
}
|
||||
}
|
||||
|
||||
func appendHandler(_ rhs: (() -> Void)?) -> ((() -> Void)?) -> (() -> Void)? {
|
||||
guard let rhs = rhs else {
|
||||
return { $0 }
|
||||
}
|
||||
return { lhs in
|
||||
guard let lhs = lhs else {
|
||||
return rhs
|
||||
}
|
||||
return {
|
||||
lhs()
|
||||
rhs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func appendHandler<T>(_ rhs: ((T) -> Void)?) -> (((T) -> Void)?) -> ((T) -> Void)? {
|
||||
guard let rhs = rhs else {
|
||||
return { $0 }
|
||||
}
|
||||
return { lhs in
|
||||
guard let lhs = lhs else {
|
||||
return rhs
|
||||
}
|
||||
return {
|
||||
lhs($0)
|
||||
rhs($0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,8 @@ import Dispatch
|
||||
/// print("Players have changed.")
|
||||
/// })
|
||||
public struct ValueObservation<Reducer: _ValueReducer> {
|
||||
var events = ValueObservationEvents<Reducer.Value>()
|
||||
|
||||
/// The reducer is created when observation starts, and is triggered upon
|
||||
/// each database change.
|
||||
var makeReducer: () -> Reducer
|
||||
@@ -37,7 +39,16 @@ public struct ValueObservation<Reducer: _ValueReducer> {
|
||||
}
|
||||
}
|
||||
|
||||
extension ValueObservation {
|
||||
struct ValueObservationEvents<Value>: Refinable {
|
||||
var onStart: (() -> Void)?
|
||||
var onTrackedRegion: ((DatabaseRegion) -> Void)?
|
||||
var onDatabaseChange: (() -> Void)?
|
||||
var onValue: ((Value) -> Void)?
|
||||
var onError: ((Error) -> Void)?
|
||||
var onCancel: (() -> Void)?
|
||||
}
|
||||
|
||||
extension ValueObservation: Refinable {
|
||||
|
||||
// MARK: - Starting Observation
|
||||
|
||||
@@ -88,7 +99,75 @@ extension ValueObservation {
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable
|
||||
{
|
||||
reader._add(observation: self, scheduling: scheduler, onError: onError, onChange: onChange)
|
||||
let observation = map(\.events) { eventHandler in
|
||||
eventHandler
|
||||
.map(\.onValue, appendHandler(onChange))
|
||||
.map(\.onError, appendHandler(onError))
|
||||
}
|
||||
observation.events.onStart?()
|
||||
return reader._add(observation: observation, scheduling: scheduler)
|
||||
}
|
||||
|
||||
// MARK: - Debugging
|
||||
|
||||
/// Performs the specified closures when ValueObservation events occur.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - onStart: A closure that executes when the observation starts.
|
||||
/// Defaults to `nil`.
|
||||
/// - onTrackedRegion: A closure that executes when the observation
|
||||
/// start tracking a database region. Defaults to `nil`.
|
||||
/// - onDatabaseChange: A closure that executes after the observation
|
||||
/// was impacted by a database change. Defaults to `nil`.
|
||||
/// - onFetch: A closure that executes when the observed value is
|
||||
/// fetched. Defaults to `nil`.
|
||||
/// - onValue: A closure that executes when the observation notifies a
|
||||
/// fresh value. Defaults to `nil`.
|
||||
/// - onError: A closure that executes when the observation fails.
|
||||
/// Defaults to `nil`.
|
||||
/// - onCancel: A closure that executes when the observation is
|
||||
/// cancelled. Defaults to `nil`.
|
||||
/// - returns: A `ValueObservation` that performs the specified closures
|
||||
/// when ValueObservation events occur.
|
||||
public func handleEvents(
|
||||
onStart: (() -> Void)? = nil,
|
||||
onTrackedRegion: ((DatabaseRegion) -> Void)? = nil,
|
||||
onDatabaseChange: (() -> Void)? = nil,
|
||||
onFetch: (() -> Void)? = nil,
|
||||
onValue: ((Reducer.Value) -> Void)? = nil,
|
||||
onError: ((Error) -> Void)? = nil,
|
||||
onCancel: (() -> Void)? = nil)
|
||||
-> ValueObservation<ValueReducers.Trace<Reducer>>
|
||||
{
|
||||
self
|
||||
.mapReducer { ValueReducers.Trace(base: $0, onFetch: onFetch ?? { }) }
|
||||
.map(\.events) { eventHandler in
|
||||
eventHandler
|
||||
.map(\.onStart, appendHandler(onStart))
|
||||
.map(\.onTrackedRegion, appendHandler(onTrackedRegion))
|
||||
.map(\.onDatabaseChange, appendHandler(onDatabaseChange))
|
||||
.map(\.onValue, appendHandler(onValue))
|
||||
.map(\.onError, appendHandler(onError))
|
||||
.map(\.onCancel, appendHandler(onCancel))
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints log messages for all ValueObservation events.
|
||||
public func print(
|
||||
_ prefix: String = "",
|
||||
to stream: TextOutputStream? = nil)
|
||||
-> ValueObservation<ValueReducers.Trace<Reducer>>
|
||||
{
|
||||
let prefix = prefix.isEmpty ? "" : "\(prefix): "
|
||||
var stream = stream ?? PrintOutputStream()
|
||||
return handleEvents(
|
||||
onStart: { stream.write("\(prefix)start") },
|
||||
onTrackedRegion: { stream.write("\(prefix)tracked region: \($0)") },
|
||||
onDatabaseChange: { stream.write("\(prefix)database did change") },
|
||||
onFetch: { stream.write("\(prefix)fetch") },
|
||||
onValue: { stream.write("\(prefix)value: \($0)") },
|
||||
onError: { stream.write("\(prefix)error: \($0)") },
|
||||
onCancel: { stream.write("\(prefix)cancel") })
|
||||
}
|
||||
|
||||
// MARK: - Fetching Values
|
||||
|
||||
@@ -3,35 +3,57 @@ import Foundation
|
||||
/// Support for ValueObservation.
|
||||
/// See DatabaseWriter.add(observation:onError:onChange:)
|
||||
final class ValueObserver<Reducer: _ValueReducer> {
|
||||
private(set) var observedRegion: DatabaseRegion? // internal for testability
|
||||
private(set) var observedRegion: DatabaseRegion? { // internal for testability
|
||||
didSet {
|
||||
if
|
||||
let onTrackedRegion = events.onTrackedRegion,
|
||||
let region = observedRegion,
|
||||
region != oldValue
|
||||
{
|
||||
onTrackedRegion(region)
|
||||
}
|
||||
}
|
||||
}
|
||||
var isCompleted: Bool { synchronized { _isCompleted } }
|
||||
let events: ValueObservationEvents<Reducer.Value>
|
||||
private var _isCompleted = false
|
||||
private var reducer: Reducer
|
||||
private let requiresWriteAccess: Bool
|
||||
private weak var writer: DatabaseWriter?
|
||||
private let scheduler: ValueObservationScheduler
|
||||
private let reduceQueue: DispatchQueue
|
||||
private let onError: (Error) -> Void
|
||||
private let onChange: (Reducer.Value) -> Void
|
||||
private var isChanged = false
|
||||
private var lock = NSRecursiveLock() // protects _isCompleted
|
||||
|
||||
init(
|
||||
events: ValueObservationEvents<Reducer.Value>,
|
||||
reducer: Reducer,
|
||||
requiresWriteAccess: Bool,
|
||||
writer: DatabaseWriter,
|
||||
reducer: Reducer,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
reduceQueue: DispatchQueue,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
scheduler: ValueObservationScheduler,
|
||||
reduceQueue: DispatchQueue)
|
||||
{
|
||||
self.writer = writer
|
||||
self.events = events
|
||||
self.reducer = reducer
|
||||
self.requiresWriteAccess = requiresWriteAccess
|
||||
self.writer = writer
|
||||
self.scheduler = scheduler
|
||||
self.reduceQueue = reduceQueue
|
||||
self.onError = onError
|
||||
self.onChange = onChange
|
||||
}
|
||||
|
||||
convenience init(
|
||||
observation: ValueObservation<Reducer>,
|
||||
writer: DatabaseWriter,
|
||||
scheduler: ValueObservationScheduler,
|
||||
reduceQueue: DispatchQueue)
|
||||
{
|
||||
self.init(
|
||||
events: observation.events,
|
||||
reducer: observation.makeReducer(),
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
writer: writer,
|
||||
scheduler: scheduler,
|
||||
reduceQueue: reduceQueue)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +82,8 @@ extension ValueObserver: TransactionObserver {
|
||||
isChanged = false
|
||||
if isCompleted { return }
|
||||
|
||||
events.onDatabaseChange?()
|
||||
|
||||
// 1. Fetch
|
||||
let fetchedValue: DatabaseFuture<Reducer.Fetched>
|
||||
if requiresWriteAccess || needsRecordingSelectedRegion {
|
||||
@@ -119,19 +143,26 @@ extension ValueObserver {
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
func complete() {
|
||||
synchronized {
|
||||
// no harm if already completed
|
||||
_isCompleted = true
|
||||
writer?.remove(transactionObserver: self)
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
synchronized {
|
||||
if _isCompleted { return }
|
||||
events.onCancel?()
|
||||
complete()
|
||||
}
|
||||
}
|
||||
|
||||
func notifyChange(_ value: Reducer.Value) {
|
||||
if isCompleted { return }
|
||||
scheduler.schedule {
|
||||
if self.isCompleted { return }
|
||||
self.onChange(value)
|
||||
self.events.onValue?(value)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,12 +173,12 @@ extension ValueObserver {
|
||||
if self._isCompleted {
|
||||
return false
|
||||
} else {
|
||||
self._isCompleted = true
|
||||
self.complete()
|
||||
return true
|
||||
}
|
||||
}
|
||||
if shouldNotify {
|
||||
self.onError(error)
|
||||
self.events.onError?(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
extension ValueReducers {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct Trace<Base: _ValueReducer>: _ValueReducer {
|
||||
var base: Base
|
||||
let onFetch: () -> Void
|
||||
public var isSelectedRegionDeterministic: Bool { base.isSelectedRegionDeterministic }
|
||||
|
||||
public func fetch(_ db: Database) throws -> Base.Fetched {
|
||||
onFetch()
|
||||
return try base.fetch(db)
|
||||
}
|
||||
|
||||
public mutating func value(_ fetched: Base.Fetched) -> Base.Value? {
|
||||
base.value(fetched)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,8 @@
|
||||
563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; };
|
||||
563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
|
||||
563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
|
||||
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; };
|
||||
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; };
|
||||
563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563C67B924628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
|
||||
@@ -782,6 +784,7 @@
|
||||
563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
|
||||
563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
|
||||
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
|
||||
563B8F99249E74E5007A48C9 /* Trace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = "<group>"; };
|
||||
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
|
||||
563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
|
||||
563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
|
||||
@@ -1711,6 +1714,7 @@
|
||||
56C0538A22ACEECD0029D27D /* Fetch.swift */,
|
||||
56C0538E22ACEECD0029D27D /* Map.swift */,
|
||||
56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */,
|
||||
563B8F99249E74E5007A48C9 /* Trace.swift */,
|
||||
56C0538C22ACEECD0029D27D /* ValueReducer.swift */,
|
||||
);
|
||||
path = ValueReducer;
|
||||
@@ -2247,6 +2251,7 @@
|
||||
5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
|
||||
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
|
||||
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */,
|
||||
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */,
|
||||
5656A88C2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
@@ -2585,6 +2590,7 @@
|
||||
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
|
||||
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
|
||||
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */,
|
||||
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */,
|
||||
5656A88B2295BD56001FF3FF /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
|
||||
@@ -135,20 +135,21 @@ 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)")!
|
||||
}
|
||||
var regions: [DatabaseRegion] = []
|
||||
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)")!
|
||||
})
|
||||
.handleEvents(onTrackedRegion: { regions.append($0) })
|
||||
|
||||
let observer = dbQueue._addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: .immediate,
|
||||
let observer = observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
results.append(count)
|
||||
notificationExpectation.fulfill()
|
||||
})
|
||||
XCTAssertEqual(observer.observedRegion!.description, "a(value),source(name)")
|
||||
results.append(count)
|
||||
notificationExpectation.fulfill()
|
||||
})
|
||||
|
||||
try withExtendedLifetime(observer) {
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -163,7 +164,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(results, [0, 1, 2, 3])
|
||||
|
||||
XCTAssertEqual(observer.observedRegion!.description, "b(value),source(name)")
|
||||
XCTAssertEqual(regions.map(\.description), [
|
||||
"a(value),source(name)",
|
||||
"b(value),source(name)"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,13 +186,16 @@ 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)")!
|
||||
}
|
||||
var regions: [DatabaseRegion] = []
|
||||
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)")!
|
||||
})
|
||||
.handleEvents(onTrackedRegion: { regions.append($0) })
|
||||
|
||||
let observer = dbQueue._addWriteOnly(
|
||||
observation: observation,
|
||||
let observer = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
@@ -197,8 +203,6 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
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
|
||||
@@ -212,7 +216,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(results, [0, 1, 2, 3])
|
||||
|
||||
XCTAssertEqual(observer.observedRegion!.description, "b(value),source(name)")
|
||||
XCTAssertEqual(regions.map(\.description), [
|
||||
"a(value),source(name)",
|
||||
"b(value),source(name)"])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,13 +90,22 @@ class ValueObservationTests: 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)
|
||||
let observer = dbQueue._addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: .immediate, // So that we can test the observedRegion
|
||||
var region: DatabaseRegion?
|
||||
let expectation = self.expectation(description: "")
|
||||
let observation = ValueObservation
|
||||
.tracking(request.fetchAll)
|
||||
.handleEvents(onTrackedRegion: {
|
||||
region = $0
|
||||
expectation.fulfill()
|
||||
})
|
||||
let observer = observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { _ in })
|
||||
XCTAssertEqual(observer.observedRegion!.description, "t(id,name)") // view is NOT tracked
|
||||
withExtendedLifetime(observer) {
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(region!.description, "t(id,name)") // view is NOT tracked
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Snapshot Optimization
|
||||
|
||||
Reference in new issue
Block a user