mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
82 lines
2.8 KiB
Swift
82 lines
2.8 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
|
|
|
|
/// If true, reducer wants to record the selected region.
|
|
///
|
|
/// _ValueReducer semantics require that this property does not depend on
|
|
/// the state of the reducer.
|
|
var isObservedRegionDeterministic: Bool { get }
|
|
|
|
// TODO: rename fetch(_ db: Database, recording selectedRegion: inout DatabaseRegion) throws -> Fetched
|
|
/// Fetches database values upon changes in an observed database region.
|
|
///
|
|
/// _ValueReducer semantics require that this method does not depend on
|
|
/// the state of the reducer.
|
|
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 in some unspecified dispatch queue.
|
|
///
|
|
/// _ValueReducer semantics require that the first invocation of this
|
|
/// method returns a non-nil value:
|
|
///
|
|
/// let reducer = MyReducer()
|
|
/// reducer.value(...) // MUST NOT be nil
|
|
/// reducer.value(...) // MAY be nil
|
|
/// reducer.value(...) // MAY be nil
|
|
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)
|
|
}
|
|
}
|
|
}
|
|
|
|
mutating func fetchAndReduce(
|
|
_ db: Database,
|
|
requiringWriteAccess: Bool)
|
|
throws -> Value?
|
|
{
|
|
let fetchedValue = try fetch(db, requiringWriteAccess: requiringWriteAccess)
|
|
return value(fetchedValue)
|
|
}
|
|
}
|
|
|
|
/// A namespace for types related to the _ValueReducer protocol.
|
|
public enum ValueReducers { }
|
|
|
|
// TODO: define an empty NeverReducer enum instead of reusing Never.
|
|
// This allows us to use Never as a marker for ValueObservation factory methods:
|
|
//
|
|
// For example, ValueObservation.tracking(_:) is, practically,
|
|
// ValueObservation<Never>.tracking(_:).
|
|
extension Never: _ValueReducer {
|
|
public var isObservedRegionDeterministic: Bool { preconditionFailure() }
|
|
public func fetch(_ db: Database) throws -> Never { preconditionFailure() }
|
|
public mutating func value(_ fetched: Never) -> Never? { }
|
|
}
|