Files
GRDB.swift/GRDB/ValueObservation/ValueReducer/ValueReducer.swift
T
Gwendal Roué 28c32c6af8 _ValueReducer is the only protocol accepted by ValueObservation
Also, we now use Never as the bottom reducer which helps us define the ValueObservation factory methods.
2020-03-11 21:38:41 +01:00

49 lines
1.6 KiB
Swift

/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The _ValueReducer protocol supports ValueObservation.
public protocol _ValueReducer {
/// The type of fetched database values
associatedtype Fetched
/// The type of observed values
associatedtype Value
/// Feches database values upon changes in an observed database region.
func fetch(_ db: Database) throws -> Fetched
/// Transforms a fetched value into an eventual observed value. Returns nil
/// when observer should not be notified.
///
/// This method runs inside a private dispatch queue.
mutating func value(_ fetched: Fetched) -> Value?
}
extension _ValueReducer {
func fetch(_ db: Database, requiringWriteAccess: Bool) throws -> Fetched {
if requiringWriteAccess {
var fetchedValue: Fetched?
try db.inSavepoint {
fetchedValue = try fetch(db)
return .commit
}
return fetchedValue!
} else {
return try db.readOnly {
try fetch(db)
}
}
}
}
/// A namespace for types related to the _ValueReducer protocol.
public enum ValueReducers { }
// This allows us to use Never as a marker for ValueObservation factory methods:
//
// For example, ValueObservation.tracking(value:) is, practically,
// ValueObservation<Never>.tracking(value:).
extension Never: _ValueReducer {
public func fetch(_ db: Database) throws -> Never { preconditionFailure() }
public mutating func value(_ fetched: Never) -> Never? { }
}