From 7c4462641e266d8cc02e4bd7ff801803dc98cac7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Oct 2018 17:16:03 +0200 Subject: [PATCH] ValueObservation creation is always done with a factory initializer --- GRDB/Core/ValueObservation.swift | 44 +++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift index 930c811f5..3af2d8613 100644 --- a/GRDB/Core/ValueObservation.swift +++ b/GRDB/Core/ValueObservation.swift @@ -133,7 +133,7 @@ public struct ValueObservation { /// /// - parameter region: a closure that returns the observed region. /// - parameter fetch: a closure that fetches a value. - public init( + init( observing region: @escaping (Database) throws -> DatabaseRegion, reducer: Reducer) { @@ -145,6 +145,41 @@ public struct ValueObservation { self.qos = .unspecified } } + + /// Creates a ValueObservation which observes *region*, and notifies the + /// values returned by the *fetch* closure whenever the observed region is + /// impacted by a database transaction. + /// + /// For example: + /// + /// let observation = ValueObservation( + /// observing: { db in try Player.all().databaseRegion(db) }, + /// fetch: { db in try Player.fetchAll(db) }) + /// + /// let observer = dbQueue.add(observation: observation) { player: [Player] in + /// print("players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `add(observation:)` method, a fresh value is + /// immediately notified on the dispatch queue which starts the observation. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `add(observation:)` is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter region: a closure that returns the observed region. + /// - parameter fetch: a closure that fetches a value. + public static func observing( + _ region: @escaping (Database) throws -> DatabaseRegion, + reducer: Reducer) + -> ValueObservation + { + return ValueObservation(observing: region, reducer: reducer) + } } // MARK: - Reducers @@ -345,9 +380,10 @@ extension ValueObservation { /// /// - parameter region: a closure that returns the observed region. /// - parameter fetch: a closure that fetches a value. - public init( - observing regions: DatabaseRegionConvertible..., + public static func observing( + _ regions: DatabaseRegionConvertible..., reducer: Reducer) + -> ValueObservation { func region(_ db: Database) throws -> DatabaseRegion { return try regions.reduce(into: DatabaseRegion()) { union, region in @@ -355,7 +391,7 @@ extension ValueObservation { } } - self.init(observing: region, reducer: reducer) + return ValueObservation(observing: region, reducer: reducer) } }