mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
Combine publishers
This commit is contained in:
1 parent
329b010bfa
commit
a0ce362197
10 files changed
+965
-2
No files matched your search
@@ -173,6 +173,18 @@
|
||||
563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
|
||||
563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
|
||||
563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */; };
|
||||
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */; };
|
||||
563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */; };
|
||||
563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */; };
|
||||
563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */; };
|
||||
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
|
||||
563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
|
||||
563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
|
||||
563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
|
||||
563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
|
||||
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
|
||||
563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.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 */; };
|
||||
@@ -1254,6 +1266,9 @@
|
||||
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>"; };
|
||||
563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
|
||||
563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = "<group>"; };
|
||||
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = "<group>"; };
|
||||
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.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>"; };
|
||||
@@ -1955,9 +1970,11 @@
|
||||
563EF4492161F179007DAACD /* Inflections.swift */,
|
||||
569BBA482291707D00478429 /* Inflections+English.swift */,
|
||||
566BE7172342542F00A8254B /* LockedBox.swift */,
|
||||
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */,
|
||||
563EF414215F87EB007DAACD /* OrderedDictionary.swift */,
|
||||
5659F4971EA8D989004A4992 /* Pool.swift */,
|
||||
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */,
|
||||
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */,
|
||||
56781B0A243F86E600650A83 /* Refinable.swift */,
|
||||
5659F4871EA8D94E004A4992 /* Utils.swift */,
|
||||
);
|
||||
@@ -2160,6 +2177,7 @@
|
||||
56A238731B9C75030082EB20 /* DatabaseError.swift */,
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */,
|
||||
560A37A31C8F625000949E71 /* DatabasePool.swift */,
|
||||
563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */,
|
||||
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
|
||||
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
|
||||
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
|
||||
@@ -2182,8 +2200,8 @@
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
sourceTree = "<group>";
|
||||
@@ -2766,6 +2784,7 @@
|
||||
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */,
|
||||
56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
565490B91D5AE236005622CB /* DatabasePool.swift in Sources */,
|
||||
563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
|
||||
@@ -2804,6 +2823,7 @@
|
||||
5659F49E1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */,
|
||||
563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */,
|
||||
565490D01D5AE252005622CB /* NSString.swift in Sources */,
|
||||
565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */,
|
||||
@@ -2836,6 +2856,7 @@
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
|
||||
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
569BBA50229170FA00478429 /* Inflections+English.swift in Sources */,
|
||||
563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */,
|
||||
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
565490C81D5AE252005622CB /* CGFloat.swift in Sources */,
|
||||
@@ -2890,6 +2911,7 @@
|
||||
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
|
||||
5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
@@ -2923,6 +2945,7 @@
|
||||
5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
|
||||
56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
563B8FB624A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
|
||||
56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
@@ -2942,6 +2965,7 @@
|
||||
569BBA4F229170F900478429 /* Inflections+English.swift in Sources */,
|
||||
5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
5617294F223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
5657AB121D10899D006283EF /* URL.swift in Sources */,
|
||||
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
@@ -3439,6 +3463,7 @@
|
||||
AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */,
|
||||
AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */,
|
||||
AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */,
|
||||
563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
AAA4DC7A230F1E0600C74B15 /* QueryInterfaceRequest.swift in Sources */,
|
||||
AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
AAA4DC7C230F1E0600C74B15 /* SQLExpression.swift in Sources */,
|
||||
@@ -3472,6 +3497,7 @@
|
||||
AAA4DC98230F1E0600C74B15 /* FTS5Tokenizer.swift in Sources */,
|
||||
AAA4DC99230F1E0600C74B15 /* BelongsToAssociation.swift in Sources */,
|
||||
AAA4DC9A230F1E0600C74B15 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
563B8FB824A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
AAA4DC9B230F1E0600C74B15 /* SerializedDatabase.swift in Sources */,
|
||||
AAA4DC9C230F1E0600C74B15 /* DatabaseSnapshot.swift in Sources */,
|
||||
AAA4DC9D230F1E0600C74B15 /* SQLExpressible.swift in Sources */,
|
||||
@@ -3491,6 +3517,7 @@
|
||||
AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */,
|
||||
AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */,
|
||||
AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */,
|
||||
563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */,
|
||||
AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */,
|
||||
AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */,
|
||||
@@ -3779,6 +3806,7 @@
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */,
|
||||
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
@@ -3812,6 +3840,7 @@
|
||||
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
|
||||
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
|
||||
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
@@ -3831,6 +3860,7 @@
|
||||
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */,
|
||||
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
|
||||
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
#if canImport(Combine)
|
||||
/// A namespace for database Combine publishers.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public enum DatabasePublishers { }
|
||||
#endif
|
||||
@@ -1,3 +1,6 @@
|
||||
#if canImport(Combine)
|
||||
import Combine
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// The protocol for all types that can fetch values from a database.
|
||||
@@ -289,6 +292,87 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseReader {
|
||||
// MARK: - Publishing Database Values
|
||||
|
||||
/// Returns a Publisher that asynchronously completes with a fetched value.
|
||||
///
|
||||
/// // DatabasePublishers.Read<[Player]>
|
||||
/// let players = dbQueue.readPublisher { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// Its value and completion are emitted on the main dispatch queue.
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<Output>(
|
||||
value: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
{
|
||||
readPublisher(receiveOn: DispatchQueue.main, value: value)
|
||||
}
|
||||
|
||||
/// Returns a Publisher that asynchronously completes with a fetched value.
|
||||
///
|
||||
/// // DatabasePublishers.Read<[Player]>
|
||||
/// let players = dbQueue.readPublisher(
|
||||
/// receiveOn: DispatchQueue.global(),
|
||||
/// value: { db in try Player.fetchAll(db) })
|
||||
///
|
||||
/// Its value and completion are emitted on `scheduler`.
|
||||
///
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<S, Output>(
|
||||
receiveOn scheduler: S,
|
||||
value: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
Deferred {
|
||||
Future { fulfill in
|
||||
self.asyncRead { dbResult in
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db) } })
|
||||
}
|
||||
}
|
||||
}
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToReadPublisher()
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that reads a value from the database. It publishes exactly
|
||||
/// one element, or an error.
|
||||
///
|
||||
/// See:
|
||||
///
|
||||
/// - `DatabaseReader.readPublisher(receiveOn:value:)`.
|
||||
/// - `DatabaseReader.readPublisher(value:)`.
|
||||
public struct Read<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Output, Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
|
||||
.init(upstream: eraseToAnyPublisher())
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabaseReader {
|
||||
// MARK: - Value Observation Support
|
||||
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
#if canImport(Combine)
|
||||
import Combine
|
||||
#endif
|
||||
|
||||
/// DatabaseRegionObservation tracks changes in the results of database
|
||||
/// requests, and notifies each database transaction whenever the
|
||||
/// database changes.
|
||||
@@ -94,6 +98,24 @@ extension DatabaseRegionObservation {
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabaseRegionObservation {
|
||||
// MARK: - Publishing Impactful Transactions
|
||||
|
||||
/// Returns a publisher that tracks changes in a database region.
|
||||
///
|
||||
/// It emits database connections on a protected dispatch queue.
|
||||
///
|
||||
/// Error completion, if any, is only emitted, synchronously,
|
||||
/// on subscription.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func publisher(in writer: DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
return DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private class DatabaseRegionObserver: TransactionObserver {
|
||||
let region: DatabaseRegion
|
||||
let onChange: (Database) -> Void
|
||||
@@ -126,3 +148,129 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
isChanged = false
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that tracks changes in a database region.
|
||||
///
|
||||
/// See `DatabaseRegionObservation.publisher(in:)`.
|
||||
public struct DatabaseRegion: Publisher {
|
||||
public typealias Output = Database
|
||||
public typealias Failure = Error
|
||||
|
||||
let writer: DatabaseWriter
|
||||
let observation: DatabaseRegionObservation
|
||||
|
||||
init(_ observation: DatabaseRegionObservation, in writer: DatabaseWriter) {
|
||||
self.writer = writer
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
observation: observation,
|
||||
downstream: subscriber)
|
||||
subscriber.receive(subscription: subscription)
|
||||
}
|
||||
}
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription
|
||||
where Downstream.Failure == Error, Downstream.Input == Database
|
||||
{
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
let writer: DatabaseWriter
|
||||
let observation: DatabaseRegionObservation
|
||||
}
|
||||
|
||||
private struct Observing {
|
||||
let downstream: Downstream
|
||||
let writer: DatabaseWriter // Retain writer until subscription is finished
|
||||
var remainingDemand: Subscribers.Demand
|
||||
}
|
||||
|
||||
private enum State {
|
||||
// Waiting for demand, not observing the database.
|
||||
case waitingForDemand(WaitingForDemand)
|
||||
|
||||
// Observing the database.
|
||||
case observing(Observing)
|
||||
|
||||
// Completed or cancelled, not observing the database.
|
||||
case finished
|
||||
}
|
||||
|
||||
// Observer is not stored in self.state because we must enter the
|
||||
// .observing state *before* the observation starts.
|
||||
private var observer: TransactionObserver?
|
||||
private var state: State
|
||||
private var lock = NSRecursiveLock() // Allow re-entrancy
|
||||
|
||||
init(
|
||||
writer: DatabaseWriter,
|
||||
observation: DatabaseRegionObservation,
|
||||
downstream: Downstream)
|
||||
{
|
||||
state = .waitingForDemand(WaitingForDemand(
|
||||
downstream: downstream,
|
||||
writer: writer,
|
||||
observation: observation))
|
||||
}
|
||||
|
||||
func request(_ demand: Subscribers.Demand) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case let .waitingForDemand(info):
|
||||
guard demand > 0 else {
|
||||
return
|
||||
}
|
||||
do {
|
||||
state = .observing(Observing(
|
||||
downstream: info.downstream,
|
||||
writer: info.writer,
|
||||
remainingDemand: demand))
|
||||
observer = try info.observation.start(
|
||||
in: info.writer,
|
||||
onChange: { [weak self] in self?.receive($0) })
|
||||
} catch {
|
||||
state = .finished
|
||||
info.downstream.receive(completion: .failure(error))
|
||||
}
|
||||
|
||||
case var .observing(info):
|
||||
info.remainingDemand += demand
|
||||
state = .observing(info)
|
||||
|
||||
case .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
lock.synchronized {
|
||||
observer = nil
|
||||
state = .finished
|
||||
}
|
||||
}
|
||||
|
||||
private func receive(_ value: Database) {
|
||||
lock.synchronized {
|
||||
if case let .observing(info) = state,
|
||||
info.remainingDemand > .none
|
||||
{
|
||||
let additionalDemand = info.downstream.receive(value)
|
||||
if case var .observing(info) = state {
|
||||
info.remainingDemand += additionalDemand
|
||||
info.remainingDemand -= 1
|
||||
state = .observing(info)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,3 +1,6 @@
|
||||
#if canImport(Combine)
|
||||
import Combine
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// The protocol for all types that can update a database.
|
||||
@@ -357,6 +360,158 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseWriter {
|
||||
// MARK: - Publishing Database Updates
|
||||
|
||||
/// Returns a Publisher that asynchronously writes into the database.
|
||||
///
|
||||
/// // DatabasePublishers.Write<Int>
|
||||
/// let newPlayerCount = dbQueue.writePublisher { db -> Int in
|
||||
/// try Player(...).insert(db)
|
||||
/// return try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Its value and completion are emitted on the main dispatch queue.
|
||||
///
|
||||
/// - parameter updates: A closure which writes in the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<Output>(
|
||||
updates: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
{
|
||||
writePublisher(receiveOn: DispatchQueue.main, updates: updates)
|
||||
}
|
||||
|
||||
/// Returns a Publisher that asynchronously writes into the database.
|
||||
///
|
||||
/// // DatabasePublishers.Write<Int>
|
||||
/// let newPlayerCount = dbQueue.writePublisher(
|
||||
/// receiveOn: DispatchQueue.global(),
|
||||
/// updates: { db -> Int in
|
||||
/// try Player(...).insert(db)
|
||||
/// return try Player.fetchCount(db)
|
||||
/// })
|
||||
///
|
||||
/// Its value and completion are emitted on `scheduler`.
|
||||
///
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter updates: A closure which writes in the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<S, Output>(
|
||||
receiveOn scheduler: S,
|
||||
updates: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
self.asyncWrite(updates, completion: { _, result in
|
||||
fulfill(result)
|
||||
})
|
||||
})
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToWritePublisher()
|
||||
}
|
||||
|
||||
/// Returns a Publisher that asynchronously writes into the database.
|
||||
///
|
||||
/// // DatabasePublishers.Write<Int>
|
||||
/// let newPlayerCount = dbQueue.writePublisher(
|
||||
/// updates: { db in try Player(...).insert(db) }
|
||||
/// thenRead: { db, _ in try Player.fetchCount(db) })
|
||||
///
|
||||
/// Its value and completion are emitted on the main dispatch queue.
|
||||
///
|
||||
/// - parameter updates: A closure which writes in the database.
|
||||
/// - parameter value: A closure which reads from the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<T, Output>(
|
||||
updates: @escaping (Database) throws -> T,
|
||||
thenRead value: @escaping (Database, T) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
{
|
||||
writePublisher(receiveOn: DispatchQueue.main, updates: updates, thenRead: value)
|
||||
}
|
||||
|
||||
|
||||
/// Returns a Publisher that asynchronously writes into the database.
|
||||
///
|
||||
/// // DatabasePublishers.Write<Int>
|
||||
/// let newPlayerCount = dbQueue.writePublisher(
|
||||
/// receiveOn: DispatchQueue.global(),
|
||||
/// updates: { db in try Player(...).insert(db) }
|
||||
/// thenRead: { db, _ in try Player.fetchCount(db) })
|
||||
///
|
||||
/// Its value and completion are emitted on `scheduler`.
|
||||
///
|
||||
/// - parameter scheduler: A Combine Scheduler.
|
||||
/// - parameter updates: A closure which writes in the database.
|
||||
/// - parameter value: A closure which reads from the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<S, T, Output>(
|
||||
receiveOn scheduler: S,
|
||||
updates: @escaping (Database) throws -> T,
|
||||
thenRead value: @escaping (Database, T) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
OnDemandFuture({ fulfill in
|
||||
self.asyncWriteWithoutTransaction { db in
|
||||
var updatesValue: T?
|
||||
do {
|
||||
try db.inTransaction {
|
||||
updatesValue = try updates(db)
|
||||
return .commit
|
||||
}
|
||||
} catch {
|
||||
fulfill(.failure(error))
|
||||
return
|
||||
}
|
||||
self.spawnConcurrentRead { dbResult in
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
|
||||
}
|
||||
}
|
||||
})
|
||||
// We don't want users to process emitted values on a
|
||||
// database dispatch queue.
|
||||
.receiveValues(on: scheduler)
|
||||
.eraseToWritePublisher()
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that writes into the database. It publishes exactly
|
||||
/// one element, or an error.
|
||||
///
|
||||
/// See:
|
||||
///
|
||||
/// - `DatabaseReader.writePublisher(updates:)`.
|
||||
/// - `DatabaseReader.writePublisher(updates:thenRead:)`.
|
||||
/// - `DatabaseReader.writePublisher(receiveOn:updates:)`.
|
||||
/// - `DatabaseReader.writePublisher(receiveOn:updates:thenRead:)`.
|
||||
public struct Write<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Output, Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
|
||||
.init(upstream: eraseToAnyPublisher())
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// A future database value, returned by the DatabaseWriter.concurrentRead(_:)
|
||||
/// method.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
#if canImport(Combine)
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
/// A publisher that eventually produces one value and then finishes or fails.
|
||||
///
|
||||
/// Like a Combine.Future wrapped in Combine.Deferred, OnDemandFuture starts
|
||||
/// producing its value on demand.
|
||||
///
|
||||
/// Unlike Combine.Future wrapped in Combine.Deferred, OnDemandFuture guarantees
|
||||
/// that it starts producing its value on demand, **synchronously**, and that
|
||||
/// it produces its value on promise completion, **synchronously**.
|
||||
///
|
||||
/// Both two extra scheduling guarantees are used by GRDBCombine in order to be
|
||||
/// able to spawn concurrent database reads right from the database writer
|
||||
/// queue, and fulfill GRDB preconditions.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
struct OnDemandFuture<Output, Failure: Error>: Publisher {
|
||||
typealias Promise = (Result<Output, Failure>) -> Void
|
||||
typealias Output = Output
|
||||
typealias Failure = Failure
|
||||
fileprivate let attemptToFulfill: (@escaping Promise) -> Void
|
||||
|
||||
init(_ attemptToFulfill: @escaping (@escaping Promise) -> Void) {
|
||||
self.attemptToFulfill = attemptToFulfill
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = OnDemandFutureSubscription(
|
||||
attemptToFulfill: attemptToFulfill,
|
||||
downstream: subscriber)
|
||||
subscriber.receive(subscription: subscription)
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription {
|
||||
typealias Promise = (Result<Downstream.Input, Downstream.Failure>) -> Void
|
||||
|
||||
private enum State {
|
||||
case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void)
|
||||
case waitingForFulfillment(downstream: Downstream)
|
||||
case finished
|
||||
}
|
||||
|
||||
private var state: State
|
||||
private let lock = NSRecursiveLock() // Allow re-entrancy
|
||||
|
||||
init(
|
||||
attemptToFulfill: @escaping (@escaping Promise) -> Void,
|
||||
downstream: Downstream)
|
||||
{
|
||||
self.state = .waitingForDemand(downstream: downstream, attemptToFulfill: attemptToFulfill)
|
||||
}
|
||||
|
||||
func request(_ demand: Subscribers.Demand) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case let .waitingForDemand(downstream: downstream, attemptToFulfill: attemptToFulfill):
|
||||
guard demand > 0 else {
|
||||
return
|
||||
}
|
||||
state = .waitingForFulfillment(downstream: downstream)
|
||||
attemptToFulfill { result in
|
||||
switch result {
|
||||
case let .success(value):
|
||||
self.receive(value)
|
||||
case let .failure(error):
|
||||
self.receive(completion: .failure(error))
|
||||
}
|
||||
}
|
||||
|
||||
case .waitingForFulfillment, .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
lock.synchronized {
|
||||
state = .finished
|
||||
}
|
||||
}
|
||||
|
||||
private func receive(_ value: Downstream.Input) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case let .waitingForFulfillment(downstream: downstream):
|
||||
state = .finished
|
||||
_ = downstream.receive(value)
|
||||
downstream.receive(completion: .finished)
|
||||
|
||||
case .waitingForDemand, .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func receive(completion: Subscribers.Completion<Downstream.Failure>) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case let .waitingForFulfillment(downstream: downstream):
|
||||
state = .finished
|
||||
downstream.receive(completion: completion)
|
||||
|
||||
case .waitingForDemand, .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,194 @@
|
||||
#if canImport(Combine)
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
/// A publisher that delivers values to its downstream subscriber on a
|
||||
/// specific scheduler.
|
||||
///
|
||||
/// Unlike Combine's Publishers.ReceiveOn, ReceiveValuesOn only re-schedule
|
||||
/// values and completion. It does not re-schedule subscription.
|
||||
///
|
||||
/// This scheduling guarantee is used by GRDBCombine in order to be able
|
||||
/// to make promises on the scheduling of database values without surprising
|
||||
/// the users as in https://forums.swift.org/t/28631.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
struct ReceiveValuesOn<Upstream: Publisher, Context: Scheduler>: Publisher {
|
||||
typealias Output = Upstream.Output
|
||||
typealias Failure = Upstream.Failure
|
||||
|
||||
fileprivate let upstream: Upstream
|
||||
fileprivate let context: Context
|
||||
fileprivate let options: Context.SchedulerOptions?
|
||||
|
||||
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = ReceiveValuesOnSubscription(
|
||||
upstream: upstream,
|
||||
context: context,
|
||||
options: options,
|
||||
downstream: subscriber)
|
||||
subscriber.receive(subscription: subscription)
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
private class ReceiveValuesOnSubscription<Upstream, Context, Downstream>: Subscription, Subscriber
|
||||
where
|
||||
Upstream: Publisher,
|
||||
Context: Scheduler,
|
||||
Downstream: Subscriber,
|
||||
Upstream.Failure == Downstream.Failure,
|
||||
Upstream.Output == Downstream.Input
|
||||
{
|
||||
private struct Target {
|
||||
let context: Context
|
||||
let options: Context.SchedulerOptions?
|
||||
let downstream: Downstream
|
||||
}
|
||||
|
||||
private enum State {
|
||||
case waitingForRequest(Upstream, Target)
|
||||
case waitingForSubscription(Target, Subscribers.Demand)
|
||||
case subscribed(Target, Subscription)
|
||||
case finished
|
||||
}
|
||||
|
||||
private var state: State
|
||||
private let lock = NSRecursiveLock()
|
||||
|
||||
init(
|
||||
upstream: Upstream,
|
||||
context: Context,
|
||||
options: Context.SchedulerOptions?,
|
||||
downstream: Downstream)
|
||||
{
|
||||
let target = Target(context: context, options: options, downstream: downstream)
|
||||
self.state = .waitingForRequest(upstream, target)
|
||||
}
|
||||
|
||||
// MARK: Subscription
|
||||
|
||||
func request(_ demand: Subscribers.Demand) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case let .waitingForRequest(upstream, target):
|
||||
state = .waitingForSubscription(target, demand)
|
||||
upstream.receive(subscriber: self)
|
||||
|
||||
case let .waitingForSubscription(target, currentDemand):
|
||||
state = .waitingForSubscription(target, demand + currentDemand)
|
||||
|
||||
case let .subscribed(_, subcription):
|
||||
subcription.request(demand)
|
||||
|
||||
case .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case .waitingForRequest, .waitingForSubscription:
|
||||
state = .finished
|
||||
|
||||
case let .subscribed(_, subcription):
|
||||
subcription.cancel()
|
||||
state = .finished
|
||||
|
||||
case .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Subscriber
|
||||
|
||||
func receive(subscription: Subscription) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case let .waitingForSubscription(target, currentDemand):
|
||||
state = .subscribed(target, subscription)
|
||||
subscription.request(currentDemand)
|
||||
|
||||
case .waitingForRequest, .subscribed, .finished:
|
||||
preconditionFailure()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func receive(_ input: Upstream.Output) -> Subscribers.Demand {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case let .subscribed(target, _):
|
||||
target.context.schedule(options: target.options) {
|
||||
self._receive(input)
|
||||
}
|
||||
case .waitingForRequest, .waitingForSubscription, .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: what problem are we creating by returning .unlimited and
|
||||
// ignoring downstream's result?
|
||||
//
|
||||
// `Publisher.receive(on:options:)` does not document its behavior
|
||||
// regarding backpressure.
|
||||
return .unlimited
|
||||
}
|
||||
|
||||
func receive(completion: Subscribers.Completion<Upstream.Failure>) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case .waitingForRequest, .waitingForSubscription:
|
||||
break
|
||||
case let .subscribed(target, _):
|
||||
target.context.schedule(options: target.options) {
|
||||
self._receive(completion: completion)
|
||||
}
|
||||
case .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func _receive(_ input: Upstream.Output) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case .waitingForRequest, .waitingForSubscription:
|
||||
break
|
||||
case let .subscribed(target, _):
|
||||
// TODO: don't ignore demand
|
||||
_ = target.downstream.receive(input)
|
||||
case .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func _receive(completion: Subscribers.Completion<Upstream.Failure>) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case .waitingForRequest, .waitingForSubscription:
|
||||
break
|
||||
case let .subscribed(target, _):
|
||||
target.downstream.receive(completion: completion)
|
||||
state = .finished
|
||||
case .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension Publisher {
|
||||
/// Specifies the scheduler on which to receive values from the publisher
|
||||
///
|
||||
/// The difference with the stock `receive(on:options:)` Combine method is
|
||||
/// that only values and completion are re-scheduled. Subscriptions are not.
|
||||
func receiveValues<S: Scheduler>(on scheduler: S, options: S.SchedulerOptions? = nil) -> ReceiveValuesOn<Self, S> {
|
||||
return ReceiveValuesOn(upstream: self, context: scheduler, options: options)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -170,3 +170,13 @@ func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension NSRecursiveLock {
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
func synchronized<T>(_ block: () throws -> T) rethrows -> T {
|
||||
lock()
|
||||
defer { unlock() }
|
||||
return try block()
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
#if canImport(Combine)
|
||||
import Combine
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// ValueObservation tracks changes in the results of database requests, and
|
||||
@@ -193,6 +196,209 @@ extension ValueObservation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
extension ValueObservation {
|
||||
// MARK: - Publishing Observed Values
|
||||
|
||||
/// Creates a publisher which tracks changes in database values.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = ValueObservation.tracking { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// let cancellable = observation
|
||||
/// .publisher(in: dbQueue)
|
||||
/// .sink(
|
||||
/// receiveCompletion: { completion in ... },
|
||||
/// receiveValue: { players: [Player] in
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
///
|
||||
/// By default, fresh values are dispatched asynchronously on the
|
||||
/// main queue. You can change this behavior by by providing a scheduler.
|
||||
///
|
||||
/// For example, `.immediate` notifies all values on the main queue as well,
|
||||
/// and the first one is immediately notified when the publisher
|
||||
/// is subscribed:
|
||||
///
|
||||
/// let cancellable = observation
|
||||
/// .publisher(
|
||||
/// in: dbQueue,
|
||||
/// scheduling: .immediate) // <-
|
||||
/// .sink(
|
||||
/// receiveCompletion: { completion in ... },
|
||||
/// receiveValue: { players: [Player] in
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
/// // <- here "fresh players" is already printed.
|
||||
///
|
||||
/// Note that the `.immediate` scheduler requires that the publisher is
|
||||
/// subscribed from the main thread. It raises a fatal error otherwise.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A Scheduler. By default, fresh values are
|
||||
/// dispatched asynchronously on the main queue.
|
||||
/// - returns: A Combine publisher
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func publisher(
|
||||
in reader: DatabaseReader,
|
||||
scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main))
|
||||
-> DatabasePublishers.Value<Reducer.Value>
|
||||
{
|
||||
return DatabasePublishers.Value(self, in: reader, scheduling: scheduler)
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
fileprivate typealias Start<T> = (
|
||||
_ onError: @escaping (Error) -> Void,
|
||||
_ onChange: @escaping (T) -> Void) -> DatabaseCancellable
|
||||
|
||||
/// A publisher that tracks changes in the database.
|
||||
///
|
||||
/// See `ValueObservation.publisher(in:scheduling:)`.
|
||||
public struct Value<Output>: Publisher {
|
||||
public typealias Failure = Error
|
||||
private let start: Start<Output>
|
||||
|
||||
init<Reducer>(
|
||||
_ observation: ValueObservation<Reducer>,
|
||||
in reader: DatabaseReader,
|
||||
scheduling scheduler: ValueObservationScheduler)
|
||||
where Reducer.Value == Output
|
||||
{
|
||||
start = { [weak reader] (onError, onChange) in
|
||||
guard let reader = reader else {
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
}
|
||||
return observation.start(
|
||||
in: reader,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = ValueSubscription(
|
||||
start: start,
|
||||
downstream: subscriber)
|
||||
subscriber.receive(subscription: subscription)
|
||||
}
|
||||
}
|
||||
|
||||
private class ValueSubscription<Downstream: Subscriber>: Subscription
|
||||
where Downstream.Failure == Error
|
||||
{
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
let start: Start<Downstream.Input>
|
||||
}
|
||||
|
||||
private struct Observing {
|
||||
let downstream: Downstream
|
||||
var remainingDemand: Subscribers.Demand
|
||||
}
|
||||
|
||||
private enum State {
|
||||
/// Waiting for demand, not observing the database.
|
||||
case waitingForDemand(WaitingForDemand)
|
||||
|
||||
/// Observing the database. Self.observer is not nil.
|
||||
case observing(Observing)
|
||||
|
||||
/// Completed or cancelled, not observing the database.
|
||||
case finished
|
||||
}
|
||||
|
||||
// Cancellable is not stored in self.state because we must enter the
|
||||
// .observing state *before* the observation starts, so that the user
|
||||
// can change the state even before the cancellable is known.
|
||||
private var cancellable: DatabaseCancellable?
|
||||
private var state: State
|
||||
private var lock = NSRecursiveLock() // Allow re-entrancy
|
||||
|
||||
init(
|
||||
start: @escaping Start<Downstream.Input>,
|
||||
downstream: Downstream)
|
||||
{
|
||||
state = .waitingForDemand(WaitingForDemand(
|
||||
downstream: downstream,
|
||||
start: start))
|
||||
}
|
||||
|
||||
func request(_ demand: Subscribers.Demand) {
|
||||
lock.synchronized {
|
||||
switch state {
|
||||
case let .waitingForDemand(info):
|
||||
guard demand > 0 else {
|
||||
return
|
||||
}
|
||||
state = .observing(Observing(
|
||||
downstream: info.downstream,
|
||||
remainingDemand: demand))
|
||||
let cancellable = info.start(
|
||||
{ [weak self] error in self?.receiveCompletion(.failure(error)) },
|
||||
{ [weak self] value in self?.receive(value) })
|
||||
|
||||
// State may have been altered (error or cancellation)
|
||||
switch state {
|
||||
case .waitingForDemand:
|
||||
preconditionFailure()
|
||||
case .observing:
|
||||
self.cancellable = cancellable
|
||||
case .finished:
|
||||
cancellable.cancel()
|
||||
}
|
||||
|
||||
case var .observing(info):
|
||||
info.remainingDemand += demand
|
||||
state = .observing(info)
|
||||
|
||||
case .finished:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
lock.synchronized {
|
||||
cancellable?.cancel()
|
||||
cancellable = nil
|
||||
state = .finished
|
||||
}
|
||||
}
|
||||
|
||||
private func receive(_ value: Downstream.Input) {
|
||||
lock.synchronized {
|
||||
if case let .observing(info) = state,
|
||||
info.remainingDemand > .none
|
||||
{
|
||||
let additionalDemand = info.downstream.receive(value)
|
||||
if case var .observing(info) = state {
|
||||
info.remainingDemand += additionalDemand
|
||||
info.remainingDemand -= 1
|
||||
state = .observing(info)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func receiveCompletion(_ completion: Subscribers.Completion<Error>) {
|
||||
lock.synchronized {
|
||||
if case let .observing(info) = state {
|
||||
cancellable = nil
|
||||
state = .finished
|
||||
info.downstream.receive(completion: completion)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
|
||||
// MARK: - Creating ValueObservation
|
||||
|
||||
@@ -91,6 +91,12 @@
|
||||
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; };
|
||||
563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; };
|
||||
563B8F9F249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; };
|
||||
563B8FB224A1CE9E007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB024A1CE9E007A48C9 /* DatabasePublishers.swift */; };
|
||||
563B8FB324A1CE9E007A48C9 /* DatabasePublishers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB024A1CE9E007A48C9 /* DatabasePublishers.swift */; };
|
||||
563B8FBA24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */; };
|
||||
563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */; };
|
||||
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */; };
|
||||
563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FBC24A1D388007A48C9 /* OnDemandFuture.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 */; };
|
||||
@@ -788,6 +794,9 @@
|
||||
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>"; };
|
||||
563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
|
||||
563B8FB024A1CE9E007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = "<group>"; };
|
||||
563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = "<group>"; };
|
||||
563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.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>"; };
|
||||
@@ -1469,9 +1478,11 @@
|
||||
563EF44C2161F196007DAACD /* Inflections.swift */,
|
||||
569BBA4B229170B300478429 /* Inflections+English.swift */,
|
||||
566BE7132342541F00A8254B /* LockedBox.swift */,
|
||||
563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */,
|
||||
563EF41E215F8A76007DAACD /* OrderedDictionary.swift */,
|
||||
5659F4971EA8D989004A4992 /* Pool.swift */,
|
||||
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */,
|
||||
563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */,
|
||||
56DF37A623D77AA0009AAA05 /* Refinable.swift */,
|
||||
5659F4871EA8D94E004A4992 /* Utils.swift */,
|
||||
);
|
||||
@@ -1659,6 +1670,7 @@
|
||||
56A238731B9C75030082EB20 /* DatabaseError.swift */,
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */,
|
||||
560A37A31C8F625000949E71 /* DatabasePool.swift */,
|
||||
563B8FB024A1CE9E007A48C9 /* DatabasePublishers.swift */,
|
||||
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
|
||||
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
|
||||
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */,
|
||||
@@ -1681,8 +1693,8 @@
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
sourceTree = "<group>";
|
||||
@@ -2157,6 +2169,7 @@
|
||||
5656A8722295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5656A85E2295BD56001FF3FF /* VirtualTableModule.swift in Sources */,
|
||||
5656A8882295BD56001FF3FF /* SQLOperators.swift in Sources */,
|
||||
563EF44E2161F196007DAACD /* Inflections.swift in Sources */,
|
||||
@@ -2190,6 +2203,7 @@
|
||||
F3BA80161CFB2876003DC1BA /* Row.swift in Sources */,
|
||||
569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
|
||||
F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */,
|
||||
563B8FBA24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */,
|
||||
5659F49D1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
@@ -2209,6 +2223,7 @@
|
||||
56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */,
|
||||
56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
563B8FB324A1CE9E007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
56C0539E22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */,
|
||||
F3BA80201CFB288C003DC1BA /* Date.swift in Sources */,
|
||||
56A8C2351D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
@@ -2497,6 +2512,7 @@
|
||||
5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5656A85D2295BD56001FF3FF /* VirtualTableModule.swift in Sources */,
|
||||
5656A8872295BD56001FF3FF /* SQLOperators.swift in Sources */,
|
||||
563EF44D2161F196007DAACD /* Inflections.swift in Sources */,
|
||||
@@ -2530,6 +2546,7 @@
|
||||
F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */,
|
||||
569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
|
||||
F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */,
|
||||
563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */,
|
||||
5659F49A1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
@@ -2549,6 +2566,7 @@
|
||||
56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */,
|
||||
56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
563B8FB224A1CE9E007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */,
|
||||
F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */,
|
||||
56A8C2321D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
|
||||
Reference in new issue
Block a user