mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Merge branch 'development' into dev/async
This commit is contained in:
commit
2a665df672
15 files changed
+1223
-44
No files matched your search
@@ -83,8 +83,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
- **Breaking Change**: [#1076](https://github.com/groue/GRDB.swift/pull/1076) by [@groue](https://github.com/groue): Require Swift 5.3
|
||||
- **New**: [#1078](https://github.com/groue/GRDB.swift/pull/1078) by [@groue](https://github.com/groue): More convenience methods (non-mutating persistence methods, and existence-checking methods)
|
||||
- **New**: [#1088](https://github.com/groue/GRDB.swift/pull/1088) by [@groue](https://github.com/groue): Shared ValueObservation
|
||||
- **New**: `DatabasePool.erase()` prevents concurrent reads until it has completed.
|
||||
- **Documentation Update**: A new [Testing for Record Existence](README.md#testing-for-record-existence) chapter describes the new `request.isEmpty(_:)`, `Record.exists(_:id:)` and `Record.exists(_:key:)` methods.
|
||||
- **Documentation Update**: A new [ValueObservation Sharing](README.md#valueobservation-sharing) chapter describes how to share database observations and spare database resources.
|
||||
|
||||
## 5.12.0
|
||||
|
||||
|
||||
@@ -205,6 +205,7 @@ It completes on the main queue, unless you provide a specific [scheduler] to the
|
||||
Database Observation publishers are based on [ValueObservation] and [DatabaseRegionObservation]. Please refer to their documentation for more information. If your application needs change notifications that are not built as Combine publishers, check the general [Database Changes Observation] chapter.
|
||||
|
||||
- [`ValueObservation.publisher(in:scheduling:)`]
|
||||
- [`SharedValueObservation.publisher()`]
|
||||
- [`DatabaseRegionObservation.publisher(in:)`]
|
||||
|
||||
|
||||
@@ -250,6 +251,22 @@ This publisher has the same behavior as ValueObservation:
|
||||
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
|
||||
|
||||
|
||||
#### `SharedValueObservation.publisher()`
|
||||
|
||||
[SharedValueObservation] tracks changes in database values. You can turn it into a Combine publisher:
|
||||
|
||||
```swift
|
||||
let sharedObservation = ValueObservation
|
||||
.tracking { db in try Player.fetchAll(db) }
|
||||
.shared(in: dbQueue)
|
||||
|
||||
// A publisher with output [Player] and failure Error
|
||||
let publisher = sharedObservation.publisher()
|
||||
```
|
||||
|
||||
This publisher has the same behavior as SharedValueObservation.
|
||||
|
||||
|
||||
#### `DatabaseRegionObservation.publisher(in:)`
|
||||
|
||||
[DatabaseRegionObservation] notifies all transactions that impact a tracked database region. You can turn it into a Combine publisher:
|
||||
@@ -374,8 +391,10 @@ let cancellable = hallOfFamePublisher.sink(
|
||||
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
|
||||
[SQLite]: http://sqlite.org
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[SharedValueObservation]: ../README.md#valueobservation-sharing
|
||||
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
|
||||
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
|
||||
[`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher
|
||||
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
|
||||
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
|
||||
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
|
||||
|
||||
@@ -14,6 +14,13 @@
|
||||
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
56012BB1257404E100B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
|
||||
560233C52724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
|
||||
560233C62724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
|
||||
560233C72724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
|
||||
560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
|
||||
560233CA2724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
|
||||
560233CB2724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
|
||||
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
@@ -573,6 +580,9 @@
|
||||
56915783231BF28B00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915781231BF28B00E1D237 /* PoolTests.swift */; };
|
||||
56915784231BF28B00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56915781231BF28B00E1D237 /* PoolTests.swift */; };
|
||||
569178491CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */; };
|
||||
5691D96A27256C3B0021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96927256C3A0021D540 /* AvailableElements.swift */; };
|
||||
5691D96B27256C3B0021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96927256C3A0021D540 /* AvailableElements.swift */; };
|
||||
5691D96C27256C3B0021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96927256C3A0021D540 /* AvailableElements.swift */; };
|
||||
569531091C9067DC00CF1A2B /* DatabaseQueueCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */; };
|
||||
5695310A1C9067DC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */; };
|
||||
5695310B1C9067DC00CF1A2B /* GRDBCrashTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */; };
|
||||
@@ -1258,6 +1268,8 @@
|
||||
/* Begin PBXFileReference section */
|
||||
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = "<group>"; };
|
||||
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
|
||||
560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
|
||||
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
|
||||
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
|
||||
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1478,6 +1490,7 @@
|
||||
5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = "<group>"; };
|
||||
56915781231BF28B00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
|
||||
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = "<group>"; };
|
||||
5691D96927256C3A0021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
|
||||
569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueCrashTests.swift; sourceTree = "<group>"; };
|
||||
569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleCrashTests.swift; sourceTree = "<group>"; };
|
||||
569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBCrashTestCase.swift; sourceTree = "<group>"; };
|
||||
@@ -1791,6 +1804,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */,
|
||||
563B06AA217EF0CC00B38F35 /* ValueObservation.swift */,
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */,
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */,
|
||||
@@ -1933,6 +1947,7 @@
|
||||
563B06BF2185CD1700B38F35 /* ValueObservation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560233C82724338800529DF3 /* SharedValueObservationTests.swift */,
|
||||
563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */,
|
||||
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
|
||||
563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */,
|
||||
@@ -1964,6 +1979,7 @@
|
||||
56419A6024A51601004967E1 /* PublisherExpectations */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5691D96927256C3A0021D540 /* AvailableElements.swift */,
|
||||
56419A6124A51601004967E1 /* Finished.swift */,
|
||||
56419A6224A51601004967E1 /* NextOne.swift */,
|
||||
56419A6324A51601004967E1 /* Next.swift */,
|
||||
@@ -2943,6 +2959,7 @@
|
||||
567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */,
|
||||
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
|
||||
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
560233C62724234F00529DF3 /* SharedValueObservation.swift in Sources */,
|
||||
56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
568ECA8C25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
|
||||
@@ -3130,6 +3147,7 @@
|
||||
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
|
||||
56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
|
||||
563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
|
||||
560233C52724234F00529DF3 /* SharedValueObservation.swift in Sources */,
|
||||
5611620925757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */,
|
||||
566BE71F2342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
@@ -3211,6 +3229,7 @@
|
||||
562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
|
||||
569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */,
|
||||
563B06F821861D8400B38F35 /* ValueObservationCountTests.swift in Sources */,
|
||||
5691D96B27256C3B0021D540 /* AvailableElements.swift in Sources */,
|
||||
56DF001C228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */,
|
||||
56A238481B9C74A90082EB20 /* RowCopiedFromStatementTests.swift in Sources */,
|
||||
56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */,
|
||||
@@ -3368,6 +3387,7 @@
|
||||
5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */,
|
||||
56F34FBB24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */,
|
||||
569BBA28228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */,
|
||||
560233CA2724338800529DF3 /* SharedValueObservationTests.swift in Sources */,
|
||||
56F34FC324B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */,
|
||||
562393641DEE06D300A6B01F /* CursorTests.swift in Sources */,
|
||||
5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */,
|
||||
@@ -3443,6 +3463,7 @@
|
||||
56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */,
|
||||
56D4966B1D81309E008276D7 /* TableRecordDeleteTests.swift in Sources */,
|
||||
563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */,
|
||||
5691D96A27256C3B0021D540 /* AvailableElements.swift in Sources */,
|
||||
56DF001B228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */,
|
||||
56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */,
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
|
||||
@@ -3600,6 +3621,7 @@
|
||||
56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */,
|
||||
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */,
|
||||
56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */,
|
||||
560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */,
|
||||
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */,
|
||||
569BBA27228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */,
|
||||
5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */,
|
||||
@@ -3727,6 +3749,7 @@
|
||||
AAA4DCCB230F1E0600C74B15 /* DatabaseRegion.swift in Sources */,
|
||||
AAA4DCCC230F1E0600C74B15 /* DatabaseQueue.swift in Sources */,
|
||||
AAA4DCCD230F1E0600C74B15 /* ValueObservation.swift in Sources */,
|
||||
560233C72724234F00529DF3 /* SharedValueObservation.swift in Sources */,
|
||||
5611620B25757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
AAA4DCCE230F1E0600C74B15 /* DatabasePromise.swift in Sources */,
|
||||
566BE7212342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
@@ -3808,6 +3831,7 @@
|
||||
AAA4DD26230F262000C74B15 /* DatabaseWriterTests.swift in Sources */,
|
||||
AAA4DD27230F262000C74B15 /* DatabasePoolFunctionTests.swift in Sources */,
|
||||
AAA4DD28230F262000C74B15 /* ValueObservationCountTests.swift in Sources */,
|
||||
5691D96C27256C3B0021D540 /* AvailableElements.swift in Sources */,
|
||||
AAA4DD29230F262000C74B15 /* AssociationPrefetchingRowTests.swift in Sources */,
|
||||
AAA4DD2A230F262000C74B15 /* RowCopiedFromStatementTests.swift in Sources */,
|
||||
AAA4DD2B230F262000C74B15 /* DerivableRequestTests.swift in Sources */,
|
||||
@@ -3965,6 +3989,7 @@
|
||||
AAA4DDAD230F262000C74B15 /* AssociationChainRowScopesTests.swift in Sources */,
|
||||
56F34FBC24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */,
|
||||
AAA4DDAE230F262000C74B15 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */,
|
||||
560233CB2724338800529DF3 /* SharedValueObservationTests.swift in Sources */,
|
||||
56F34FC424B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */,
|
||||
AAA4DDAF230F262000C74B15 /* CursorTests.swift in Sources */,
|
||||
AAA4DDB1230F262000C74B15 /* FoundationNSStringTests.swift in Sources */,
|
||||
@@ -4092,6 +4117,7 @@
|
||||
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
|
||||
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */,
|
||||
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
|
||||
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
import Foundation
|
||||
|
||||
/// Controls the extent of the shared database observation
|
||||
/// of `SharedValueObservation`.
|
||||
public enum SharedValueObservationExtent {
|
||||
/// The `SharedValueObservation` starts a single database observation, which
|
||||
/// ends when the `SharedValueObservation` is deallocated and all
|
||||
/// subscriptions terminated.
|
||||
///
|
||||
/// This extent prevents the shared observation from recovering from
|
||||
/// database errors. To recover from database errors, create a new shared
|
||||
/// `SharedValueObservation` instance.
|
||||
case observationLifetime
|
||||
|
||||
/// The `SharedValueObservation` ends database observation when the number
|
||||
/// of subscriptions drops down to zero. The database observation restarts
|
||||
/// on the next subscription.
|
||||
///
|
||||
/// Database errors can be recovered by resubscribing to the
|
||||
/// shared observation.
|
||||
case whileObserved
|
||||
}
|
||||
|
||||
extension ValueObservation {
|
||||
/// Returns a shared value observation that shares a single underlying
|
||||
/// database observation for all subscriptions, and thus spares
|
||||
/// database resources.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let sharedObservation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(in: dbQueue)
|
||||
///
|
||||
/// The sharing only applies if you start observing the database from the
|
||||
/// same `SharedValueObservation` instance:
|
||||
///
|
||||
/// // NOT shared
|
||||
/// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
|
||||
/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
|
||||
///
|
||||
/// // Shared
|
||||
/// let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue)
|
||||
/// let cancellable1 = sharedObservation.start(...)
|
||||
/// let cancellable2 = sharedObservation.start(...)
|
||||
///
|
||||
/// By default, fresh values are dispatched asynchronously on the
|
||||
/// main queue. You can change this behavior 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 start() method
|
||||
/// is called:
|
||||
///
|
||||
/// let sharedObservation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(
|
||||
/// in: dbQueue,
|
||||
/// scheduling: .immediate) // <-
|
||||
///
|
||||
/// let cancellable = try sharedObservation.start(
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { players: [Player] in
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
/// // <- here "fresh players" is already printed.
|
||||
///
|
||||
/// Note that the `.immediate` scheduler requires that the observation is
|
||||
/// subscribed from the main thread. It raises a fatal error otherwise.
|
||||
///
|
||||
/// A shared observation starts observing the database as soon as it is
|
||||
/// subscribed. You can choose if database observation should stop, or not,
|
||||
/// when its number of subscriptions drops down to zero, with the `extent`
|
||||
/// parameter. See `SharedValueObservationExtent` for available options.
|
||||
///
|
||||
/// - parameter reader: A DatabaseReader.
|
||||
/// - parameter scheduler: A Scheduler. By default, fresh values are
|
||||
/// dispatched asynchronously on the main queue.
|
||||
/// - parameter extent: The extent of the shared database observation.
|
||||
/// - returns: A `SharedValueObservation`
|
||||
public func shared(
|
||||
in reader: DatabaseReader,
|
||||
scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main),
|
||||
extent: SharedValueObservationExtent = .whileObserved)
|
||||
-> SharedValueObservation<Reducer.Value>
|
||||
{
|
||||
SharedValueObservation(scheduling: scheduler, extent: extent) { onError, onChange in
|
||||
self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared value observation that shares a single underlying database
|
||||
/// observation for all subscriptions, and thus spares database resources.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let sharedObservation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(in: dbQueue)
|
||||
///
|
||||
/// let cancellable = try sharedObservation.start(
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { players: [Player] in
|
||||
/// print("Players have changed.")
|
||||
/// })
|
||||
///
|
||||
/// The sharing only applies if you start observing the database from the
|
||||
/// same `SharedValueObservation` instance:
|
||||
///
|
||||
/// // NOT shared
|
||||
/// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
|
||||
/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
|
||||
///
|
||||
/// // Shared
|
||||
/// let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue)
|
||||
/// let cancellable1 = sharedObservation.start(...)
|
||||
/// let cancellable2 = sharedObservation.start(...)
|
||||
public final class SharedValueObservation<Element> {
|
||||
private let scheduler: ValueObservationScheduler
|
||||
private let extent: SharedValueObservationExtent
|
||||
private let startObservation: ValueObservationStart<Element>
|
||||
private let lock = NSRecursiveLock() // support synchronous observation events
|
||||
|
||||
// protected by lock
|
||||
private var clients: [Client]
|
||||
private var isObserving = false
|
||||
private var cancellable: AnyDatabaseCancellable?
|
||||
private var lastResult: Result<Element, Error>?
|
||||
|
||||
private final class Client {
|
||||
var onError: (Error) -> Void
|
||||
var onChange: (Element) -> Void
|
||||
|
||||
init(onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) {
|
||||
self.onError = onError
|
||||
self.onChange = onChange
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate init(
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
extent: SharedValueObservationExtent,
|
||||
startObservation: @escaping ValueObservationStart<Element>)
|
||||
{
|
||||
self.scheduler = scheduler
|
||||
self.extent = extent
|
||||
self.startObservation = startObservation
|
||||
self.clients = []
|
||||
}
|
||||
|
||||
/// Starts observing the database.
|
||||
///
|
||||
/// The observation lasts until the returned cancellable is cancelled
|
||||
/// or deallocated.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let sharedObservation = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(in: dbQueue)
|
||||
///
|
||||
/// let cancellable = try sharedObservation.start(
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { players: [Player] in
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
///
|
||||
/// - parameter onError: A closure that is provided eventual errors that
|
||||
/// happen during observation
|
||||
/// - parameter onChange: A closure that is provided fresh values
|
||||
/// - returns: a DatabaseCancellable
|
||||
public func start(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Element) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
synchronized {
|
||||
// Support for reentrancy: a shared immediate observation is
|
||||
// started from the first value notification of that same shared
|
||||
// immediate observation. Yeah, users are nasty.
|
||||
// In this case, self.cancellable is still nil, because we are
|
||||
// still waiting for the upstream ValueObservation to start.
|
||||
// But we must not start another one.
|
||||
let needsStart = !isObserving
|
||||
|
||||
// State change
|
||||
let client = Client(onError: onError, onChange: onChange)
|
||||
clients.append(client)
|
||||
isObserving = true
|
||||
|
||||
// Side effect
|
||||
if needsStart {
|
||||
// Self retains the cancellable, so don't have the cancellable retain self.
|
||||
cancellable = AnyDatabaseCancellable(startObservation(
|
||||
// onError
|
||||
{ [weak self] error in
|
||||
self?.handleError(error)
|
||||
},
|
||||
// onChange
|
||||
{ [weak self] element in
|
||||
self?.handleChange(element)
|
||||
}))
|
||||
} else if let result = lastResult {
|
||||
// Notify last result as an initial value
|
||||
scheduler.scheduleInitial {
|
||||
switch result {
|
||||
case let .failure(error):
|
||||
onError(error)
|
||||
case let .success(value):
|
||||
onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return AnyDatabaseCancellable {
|
||||
// Retain shared observation (self) until client cancels
|
||||
self.handleCancel(client)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
/// Creates a publisher which tracks changes in database values.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let publisher = ValueObservation
|
||||
/// .tracking { db in try Player.fetchAll(db) }
|
||||
/// .shared(in: dbQueue)
|
||||
/// .publisher()
|
||||
///
|
||||
/// let cancellable = publisher.sink(
|
||||
/// receiveCompletion: { completion in ... },
|
||||
/// receiveValue: { players: [Player] in
|
||||
/// print("fresh players: \(players)")
|
||||
/// })
|
||||
///
|
||||
/// - returns: A Combine publisher
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func publisher() -> DatabasePublishers.Value<Element> {
|
||||
DatabasePublishers.Value { onError, onChange in
|
||||
self.start(onError: onError, onChange: onChange)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func handleError(_ error: Error) {
|
||||
synchronized {
|
||||
let notifiedClients = clients
|
||||
|
||||
// State change
|
||||
clients = []
|
||||
if extent == .whileObserved {
|
||||
isObserving = false
|
||||
cancellable = nil
|
||||
lastResult = nil
|
||||
} else {
|
||||
lastResult = .failure(error)
|
||||
}
|
||||
|
||||
// Side effect
|
||||
for client in notifiedClients {
|
||||
client.onError(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleChange(_ value: Element) {
|
||||
synchronized {
|
||||
// State change
|
||||
lastResult = .success(value)
|
||||
|
||||
// Side effect
|
||||
for client in clients {
|
||||
client.onChange(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handleCancel(_ client: Client) {
|
||||
synchronized {
|
||||
// State change
|
||||
clients.removeFirst(where: { $0 === client })
|
||||
if clients.isEmpty && extent == .whileObserved {
|
||||
isObserving = false
|
||||
cancellable = nil
|
||||
lastResult = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func synchronized<T>(_ execute: () throws -> T) rethrows -> T {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return try execute()
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,11 @@ struct ValueObservationEvents: Refinable {
|
||||
var didCancel: (() -> Void)?
|
||||
}
|
||||
|
||||
typealias ValueObservationStart<T> = (
|
||||
_ onError: @escaping (Error) -> Void,
|
||||
_ onChange: @escaping (T) -> Void)
|
||||
-> DatabaseCancellable
|
||||
|
||||
extension ValueObservation: Refinable {
|
||||
|
||||
// MARK: - Starting Observation
|
||||
@@ -90,6 +95,9 @@ extension ValueObservation: Refinable {
|
||||
/// })
|
||||
/// // <- here "fresh players" is already printed.
|
||||
///
|
||||
/// Note that the `.immediate` scheduler requires that the observation 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.
|
||||
@@ -367,39 +375,30 @@ extension ValueObservation {
|
||||
scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main))
|
||||
-> DatabasePublishers.Value<Reducer.Value>
|
||||
{
|
||||
return DatabasePublishers.Value(self, in: reader, scheduling: scheduler)
|
||||
DatabasePublishers.Value { [weak reader] (onError, onChange) in
|
||||
guard let reader = reader else {
|
||||
return AnyDatabaseCancellable(cancel: { })
|
||||
}
|
||||
return self.start(
|
||||
in: reader,
|
||||
scheduling: scheduler,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@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>
|
||||
private let start: ValueObservationStart<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)
|
||||
}
|
||||
init(start: @escaping ValueObservationStart<Output>) {
|
||||
self.start = start
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
@@ -415,7 +414,7 @@ extension DatabasePublishers {
|
||||
{
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
let start: Start<Downstream.Input>
|
||||
let start: ValueObservationStart<Downstream.Input>
|
||||
}
|
||||
|
||||
private struct Observing {
|
||||
@@ -442,7 +441,7 @@ extension DatabasePublishers {
|
||||
private var lock = NSRecursiveLock() // Allow re-entrancy
|
||||
|
||||
init(
|
||||
start: @escaping Start<Downstream.Input>,
|
||||
start: @escaping ValueObservationStart<Downstream.Input>,
|
||||
downstream: Downstream)
|
||||
{
|
||||
state = .waitingForDemand(WaitingForDemand(
|
||||
|
||||
@@ -59,6 +59,14 @@ public class ValueObservationScheduler {
|
||||
/// - important: this scheduler requires that the observation is started
|
||||
/// from the main queue. A fatal error is raised otherwise.
|
||||
public static let immediate = ValueObservationScheduler(impl: ImmediateImpl())
|
||||
|
||||
func scheduleInitial(_ action: @escaping () -> Void) {
|
||||
if immediateInitialValue() {
|
||||
action()
|
||||
} else {
|
||||
schedule(action)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private protocol ValueObservationSchedulerImpl {
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
56012B6B2573FAE700B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */; };
|
||||
56012B81257404A400B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B80257404A300B4925B /* CommonTableExpression.swift */; };
|
||||
56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B80257404A300B4925B /* CommonTableExpression.swift */; };
|
||||
560233CE2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */; };
|
||||
560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */; };
|
||||
560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233D027243A9100529DF3 /* SharedValueObservation.swift */; };
|
||||
560233D227243A9200529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233D027243A9100529DF3 /* SharedValueObservation.swift */; };
|
||||
56043296228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
56043297228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
@@ -380,6 +384,8 @@
|
||||
5690C3451D23E82A00E59934 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
|
||||
5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578B231BF2BE00E1D237 /* PoolTests.swift */; };
|
||||
5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691578B231BF2BE00E1D237 /* PoolTests.swift */; };
|
||||
5691D96F27256C490021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96D27256C490021D540 /* AvailableElements.swift */; };
|
||||
5691D97027256C490021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D96D27256C490021D540 /* AvailableElements.swift */; };
|
||||
56959620222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */; };
|
||||
56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */; };
|
||||
56959636222D058B002CB7C9 /* AssociationHasManySQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56959635222D058B002CB7C9 /* AssociationHasManySQLTests.swift */; };
|
||||
@@ -768,6 +774,8 @@
|
||||
/* Begin PBXFileReference section */
|
||||
56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = "<group>"; };
|
||||
56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
|
||||
560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
|
||||
560233D027243A9100529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
|
||||
56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
|
||||
560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
|
||||
5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -992,6 +1000,7 @@
|
||||
5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = "<group>"; };
|
||||
5691578B231BF2BE00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = "<group>"; };
|
||||
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = "<group>"; };
|
||||
5691D96D27256C490021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = "<group>"; };
|
||||
569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = "<group>"; };
|
||||
569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolSchemaCacheTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1265,6 +1274,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */,
|
||||
560233D027243A9100529DF3 /* SharedValueObservation.swift */,
|
||||
5613ED5921A95E6100DC7A68 /* ValueObservation.swift */,
|
||||
563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */,
|
||||
564CE43B21AA955B00652B19 /* ValueObserver.swift */,
|
||||
@@ -1404,6 +1414,7 @@
|
||||
563B06DB2185E04E00B38F35 /* ValueObservation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */,
|
||||
563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */,
|
||||
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
|
||||
563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */,
|
||||
@@ -1447,6 +1458,7 @@
|
||||
56419A7924A51614004967E1 /* PublisherExpectations */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5691D96D27256C490021D540 /* AvailableElements.swift */,
|
||||
56419A7A24A51614004967E1 /* Finished.swift */,
|
||||
56419A7B24A51614004967E1 /* NextOne.swift */,
|
||||
56419A7C24A51614004967E1 /* Next.swift */,
|
||||
@@ -2362,6 +2374,7 @@
|
||||
5656A8842295BD56001FF3FF /* SQLExpression.swift in Sources */,
|
||||
5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */,
|
||||
560233D227243A9200529DF3 /* SharedValueObservation.swift in Sources */,
|
||||
5656A85A2295BD56001FF3FF /* SQLGenerationContext.swift in Sources */,
|
||||
5690C3451D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5611626C2576BF9D007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
@@ -2493,6 +2506,7 @@
|
||||
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
|
||||
F3BA804C1CFB2B24003DC1BA /* GRDBTestCase.swift in Sources */,
|
||||
56959620222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */,
|
||||
560233CE2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */,
|
||||
5698ACBD1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
|
||||
5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
|
||||
562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
|
||||
@@ -2514,6 +2528,7 @@
|
||||
5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */,
|
||||
5657AB551D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
|
||||
5665F869203EF4650084C6C0 /* ColumnInfoTests.swift in Sources */,
|
||||
5691D97027256C490021D540 /* AvailableElements.swift in Sources */,
|
||||
F3BA81291CFB3063003DC1BA /* RecordInitializersTests.swift in Sources */,
|
||||
56419C8424A51D6F004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
|
||||
56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
|
||||
@@ -2726,6 +2741,7 @@
|
||||
5656A8832295BD56001FF3FF /* SQLExpression.swift in Sources */,
|
||||
5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */,
|
||||
560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */,
|
||||
5656A8592295BD56001FF3FF /* SQLGenerationContext.swift in Sources */,
|
||||
5690C3421D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5611626B2576BF9D007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
@@ -2857,6 +2873,7 @@
|
||||
F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */,
|
||||
56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */,
|
||||
5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
|
||||
560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */,
|
||||
56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */,
|
||||
562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */,
|
||||
563B071221862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */,
|
||||
@@ -2878,6 +2895,7 @@
|
||||
5698AC8C1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */,
|
||||
5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */,
|
||||
F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
5691D96F27256C490021D540 /* AvailableElements.swift in Sources */,
|
||||
56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
|
||||
56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */,
|
||||
F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */,
|
||||
|
||||
@@ -5817,6 +5817,7 @@ Tracked changes are insertions, updates, and deletions that impact the tracked v
|
||||
- [ValueObservation Usage](#valueobservation-usage)
|
||||
- [ValueObservation Scheduling](#valueobservation-scheduling)
|
||||
- [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ...
|
||||
- [ValueObservation Sharing](#valueobservation-sharing)
|
||||
- [ValueObservation Performance](#valueobservation-performance)
|
||||
- :blue_book: [Combine Publisher](Documentation/Combine.md#database-observation)
|
||||
|
||||
@@ -6146,6 +6147,86 @@ let observation = ValueObservation
|
||||
See also [ValueObservation.handleEvents](#valueobservationhandleevents).
|
||||
|
||||
|
||||
### ValueObservation Sharing
|
||||
|
||||
**Sharing a database observation spares database resources.**
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
// SharedValueObservation<[Player]>
|
||||
let sharedObservation = ValueObservation
|
||||
.tracking { db in try Player.fetchAll(db) }
|
||||
.shared(in: dbQueue)
|
||||
|
||||
let cancellable = try sharedObservation.start(
|
||||
onError: { error in ... },
|
||||
onChange: { players: [Player] in
|
||||
print("fresh players: \(players)")
|
||||
})
|
||||
```
|
||||
|
||||
The sharing only applies if you start observing the database from the same `SharedValueObservation` instance:
|
||||
|
||||
```swift
|
||||
// NOT shared
|
||||
let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
|
||||
let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
|
||||
|
||||
// Shared
|
||||
let sharedObservation = ValueObservation.tracking { db in ... }.shared(in: dbQueue)
|
||||
let cancellable1 = sharedObservation.start(...)
|
||||
let cancellable2 = sharedObservation.start(...)
|
||||
```
|
||||
|
||||
By default, fresh values are dispatched asynchronously on the main queue. You can change this behavior (see [ValueObservation Scheduling](#valueobservation-scheduling) for more information):
|
||||
|
||||
```swift
|
||||
let sharedObservation = ValueObservation
|
||||
.tracking { db in try Player.fetchAll(db) }
|
||||
.shared(in: dbQueue, scheduling: .immediate)
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~
|
||||
```
|
||||
|
||||
A shared observation starts observing the database as soon as it is subscribed. You can choose if database observation should stop, or not, when its number of subscriptions drops down to zero, with the `extent` parameter:
|
||||
|
||||
```swift
|
||||
// The default: stops observing the database when the number of subscriptions
|
||||
// drops down to zero, and restart database observation on the next subscription.
|
||||
//
|
||||
// Database errors can be recovered by resubscribing to the shared observation.
|
||||
let sharedObservation = ValueObservation
|
||||
.tracking { db in try Player.fetchAll(db) }
|
||||
.shared(in: dbQueue, extent: .whileObserved)
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
// Only stops observing the database when the shared observation is deallocated,
|
||||
// and all subscriptions are cancelled.
|
||||
//
|
||||
// This extent prevents the shared observation from recovering from database
|
||||
// errors. To recover from database errors, create a new shared
|
||||
// SharedValueObservation instance.
|
||||
let sharedObservation = ValueObservation
|
||||
.tracking { db in try Player.fetchAll(db) }
|
||||
.shared(in: dbQueue, extent: .observationLifetime)
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
```
|
||||
|
||||
> :point_up: **Note**: `ValueObservation` and `SharedValueObservation` are nearly identical, but there are a few differences you should be aware of:
|
||||
>
|
||||
> - `SharedValueObservation` has no [operator](#valueobservation-operators) such as `map`. As a replacement, you may use Combine apis:
|
||||
>
|
||||
> ```swift
|
||||
> let sharedObservation = ValueObservation.tracking { ... }.shared(in: dbQueue)
|
||||
> let cancellable = try sharedObservation
|
||||
> .publisher() // Turn shared observation into a Combine Publisher
|
||||
> .map { ... } // The map operator from Combine
|
||||
> .sink(...)
|
||||
> ```
|
||||
>
|
||||
> - Unlike `ValueObservation`, `SharedValueObservation` prevents the database from closing. As long as there exists a `SharedValueObservation` instance, or an active suscription to a shared observation, the database connection won't close.
|
||||
|
||||
|
||||
### ValueObservation Performance
|
||||
|
||||
This chapter further describes runtime aspects of ValueObservation, and provides some optimization tips for demanding applications.
|
||||
@@ -6168,20 +6249,7 @@ When needed, you can help GRDB optimize observations and reduce database content
|
||||
|
||||
2. :bulb: **Tip**: Share observations when possible.
|
||||
|
||||
Each call to the `start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider sharing a single active observation.
|
||||
|
||||
For example, with RxSwift and RxGRDB, you can use the `share(replay:scope:)` operator:
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
import RxGRDB
|
||||
import RxSwift
|
||||
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
let observable = observation.rx
|
||||
.observe(in: dbQueue)
|
||||
.share(replay: 1, scope: .whileConnected)
|
||||
```
|
||||
Each call to `ValueObservation.start` method triggers independent values refreshes. When several components of your app are interested in the same value, consider [sharing the observation](#valueobservation-sharing).
|
||||
|
||||
3. :bulb: **Tip**: Use a [database pool](#database-pools), because it can perform multi-threaded database accesses.
|
||||
|
||||
|
||||
@@ -443,6 +443,8 @@
|
||||
5641A1BD24A540D6004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5641A19F24A540D6004967E1 /* PublisherExpectation.swift */; };
|
||||
564A2026226B89E1001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; };
|
||||
564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; };
|
||||
5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
|
||||
5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
|
||||
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
|
||||
98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE2436BF42B9FCD6552E7076 /* Pods_GRDBTests.framework */; };
|
||||
F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; };
|
||||
@@ -672,6 +674,7 @@
|
||||
564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
|
||||
6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
83BFB5733A86DAA3D0BEE684 /* Pods-GRDBTestsEncrypted.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
@@ -727,6 +730,7 @@
|
||||
5641A19724A540D6004967E1 /* PublisherExpectations */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5691D97427257CE40021D540 /* AvailableElements.swift */,
|
||||
5641A19824A540D6004967E1 /* Finished.swift */,
|
||||
5641A19924A540D6004967E1 /* NextOne.swift */,
|
||||
5641A19A24A540D6004967E1 /* Next.swift */,
|
||||
@@ -1228,6 +1232,7 @@
|
||||
56419E3124A54062004967E1 /* SQLLiteralTests.swift in Sources */,
|
||||
56419E5924A54062004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
|
||||
56419DC524A54062004967E1 /* AssociationHasManyOrderingTests.swift in Sources */,
|
||||
5691D97527257CE40021D540 /* AvailableElements.swift in Sources */,
|
||||
56419E1B24A54062004967E1 /* RowFetchTests.swift in Sources */,
|
||||
56419ED924A54063004967E1 /* AssociationHasOneSQLTests.swift in Sources */,
|
||||
56419EAB24A54063004967E1 /* DatabaseValueTests.swift in Sources */,
|
||||
@@ -1451,6 +1456,7 @@
|
||||
56419E3224A54062004967E1 /* SQLLiteralTests.swift in Sources */,
|
||||
56419E5A24A54062004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
|
||||
56419DC624A54062004967E1 /* AssociationHasManyOrderingTests.swift in Sources */,
|
||||
5691D97627257CE40021D540 /* AvailableElements.swift in Sources */,
|
||||
56419E1C24A54062004967E1 /* RowFetchTests.swift in Sources */,
|
||||
56419EDA24A54063004967E1 /* AssociationHasOneSQLTests.swift in Sources */,
|
||||
56419EAC24A54063004967E1 /* DatabaseValueTests.swift in Sources */,
|
||||
|
||||
@@ -445,6 +445,8 @@
|
||||
564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; };
|
||||
564A2159226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; };
|
||||
564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; };
|
||||
5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
|
||||
5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
|
||||
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
|
||||
E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */; };
|
||||
F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; };
|
||||
@@ -675,6 +677,7 @@
|
||||
564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; };
|
||||
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
|
||||
67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -717,6 +720,7 @@
|
||||
5641A16124A540C7004967E1 /* PublisherExpectations */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5691D97127257C930021D540 /* AvailableElements.swift */,
|
||||
5641A16224A540C7004967E1 /* Finished.swift */,
|
||||
5641A16324A540C7004967E1 /* NextOne.swift */,
|
||||
5641A16424A540C7004967E1 /* Next.swift */,
|
||||
@@ -1234,6 +1238,7 @@
|
||||
56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */,
|
||||
5641A04A24A540A1004967E1 /* FoundationNSStringTests.swift in Sources */,
|
||||
5641A17824A540C7004967E1 /* Next.swift in Sources */,
|
||||
5691D97227257C930021D540 /* AvailableElements.swift in Sources */,
|
||||
5641A09624A540A1004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
|
||||
5641A0EC24A540A1004967E1 /* AssociationPrefetchingObservationTests.swift in Sources */,
|
||||
5641A01824A540A1004967E1 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
@@ -1457,6 +1462,7 @@
|
||||
56419FCB24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */,
|
||||
5641A04B24A540A1004967E1 /* FoundationNSStringTests.swift in Sources */,
|
||||
5641A17924A540C7004967E1 /* Next.swift in Sources */,
|
||||
5691D97327257C930021D540 /* AvailableElements.swift in Sources */,
|
||||
5641A09724A540A1004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
|
||||
5641A0ED24A540A1004967E1 /* AssociationPrefetchingObservationTests.swift in Sources */,
|
||||
5641A01924A540A1004967E1 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
|
||||
@@ -6,10 +6,21 @@ public enum PublisherExpectations { }
|
||||
|
||||
/// The base protocol for PublisherExpectation. It is an implementation detail
|
||||
/// that you are not supposed to use, as shown by the underscore prefix.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _PublisherExpectationBase {
|
||||
/// Sets up an XCTestExpectation. This method is an implementation detail
|
||||
/// that you are not supposed to use, as shown by the underscore prefix.
|
||||
func _setup(_ expectation: XCTestExpectation)
|
||||
|
||||
/// Returns an object that waits for the expectation. If nil, expectation
|
||||
/// is waited by the XCTestCase.
|
||||
func _makeWaiter() -> XCTWaiter?
|
||||
}
|
||||
|
||||
extension _PublisherExpectationBase {
|
||||
/// :nodoc:
|
||||
public func _makeWaiter() -> XCTWaiter? { nil }
|
||||
}
|
||||
|
||||
/// The protocol for publisher expectations.
|
||||
@@ -94,7 +105,11 @@ extension XCTestCase {
|
||||
{
|
||||
let expectation = self.expectation(description: description)
|
||||
publisherExpectation._setup(expectation)
|
||||
wait(for: [expectation], timeout: timeout)
|
||||
if let waiter = publisherExpectation._makeWaiter() {
|
||||
waiter.wait(for: [expectation], timeout: timeout)
|
||||
} else {
|
||||
wait(for: [expectation], timeout: timeout)
|
||||
}
|
||||
return try publisherExpectation.get()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
#if canImport(Combine)
|
||||
import XCTest
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension PublisherExpectations {
|
||||
/// A publisher expectation which waits for the timeout to expire, or
|
||||
/// the recorded publisher to complete.
|
||||
///
|
||||
/// When waiting for this expectation, the publisher error is thrown if
|
||||
/// the publisher fails before the expectation has expired.
|
||||
///
|
||||
/// Otherwise, an array of all elements published before the expectation
|
||||
/// has expired is returned.
|
||||
///
|
||||
/// Unlike other expectations, `AvailableElements` does not make a test fail
|
||||
/// on timeout expiration. It just returns the elements published so far.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // SUCCESS: no timeout, no error
|
||||
/// func testTimerPublishesIncreasingDates() throws {
|
||||
/// let publisher = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
|
||||
/// let recorder = publisher.record()
|
||||
/// let dates = try wait(for: recorder.availableElements, timeout: ...)
|
||||
/// XCTAssertEqual(dates.sorted(), dates)
|
||||
/// }
|
||||
public struct AvailableElements<Input, Failure: Error>: PublisherExpectation {
|
||||
let recorder: Recorder<Input, Failure>
|
||||
|
||||
public func _makeWaiter() -> XCTWaiter? { Waiter() }
|
||||
|
||||
public func _setup(_ expectation: XCTestExpectation) {
|
||||
recorder.fulfillOnCompletion(expectation)
|
||||
}
|
||||
|
||||
/// Returns all elements published so far, or throws an error if the
|
||||
/// publisher has failed.
|
||||
public func get() throws -> [Input] {
|
||||
try recorder.value { (elements, completion, remainingElements, consume) in
|
||||
if case let .failure(error) = completion {
|
||||
throw error
|
||||
}
|
||||
consume(remainingElements.count)
|
||||
return elements
|
||||
}
|
||||
}
|
||||
|
||||
/// A waiter that waits but never fails
|
||||
private class Waiter: XCTWaiter, XCTWaiterDelegate {
|
||||
init() {
|
||||
super.init(delegate: nil)
|
||||
delegate = self
|
||||
}
|
||||
|
||||
func waiter(_ waiter: XCTWaiter, didTimeoutWithUnfulfilledExpectations unfulfilledExpectations: [XCTestExpectation]) { }
|
||||
func waiter(_ waiter: XCTWaiter, fulfillmentDidViolateOrderingConstraintsFor expectation: XCTestExpectation, requiredExpectation: XCTestExpectation) { }
|
||||
func waiter(_ waiter: XCTWaiter, didFulfillInvertedExpectation expectation: XCTestExpectation) { }
|
||||
func nestedWaiter(_ waiter: XCTWaiter, wasInterruptedByTimedOutWaiter outerWaiter: XCTWaiter) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -277,21 +277,46 @@ public class Recorder<Input, Failure: Error>: Subscriber {
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension PublisherExpectations {
|
||||
/// The type of the publisher expectation returned by Recorder.completion
|
||||
/// The type of the publisher expectation returned by `Recorder.completion`.
|
||||
public typealias Completion<Input, Failure: Error> = Map<Recording<Input, Failure>, Subscribers.Completion<Failure>>
|
||||
|
||||
/// The type of the publisher expectation returned by Recorder.elements
|
||||
/// The type of the publisher expectation returned by `Recorder.elements`.
|
||||
public typealias Elements<Input, Failure: Error> = Map<Recording<Input, Failure>, [Input]>
|
||||
|
||||
/// The type of the publisher expectation returned by Recorder.last
|
||||
/// The type of the publisher expectation returned by `Recorder.last`.
|
||||
public typealias Last<Input, Failure: Error> = Map<Elements<Input, Failure>, Input?>
|
||||
|
||||
/// The type of the publisher expectation returned by Recorder.single
|
||||
/// The type of the publisher expectation returned by `Recorder.single`.
|
||||
public typealias Single<Input, Failure: Error> = Map<Elements<Input, Failure>, Input>
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension Recorder {
|
||||
/// Returns a publisher expectation which waits for the timeout to expire,
|
||||
/// or the recorded publisher to complete.
|
||||
///
|
||||
/// When waiting for this expectation, the publisher error is thrown if
|
||||
/// the publisher fails before the expectation has expired.
|
||||
///
|
||||
/// Otherwise, an array of all elements published before the expectation
|
||||
/// has expired is returned.
|
||||
///
|
||||
/// Unlike other expectations, `availableElements` does not make a test fail
|
||||
/// on timeout expiration. It just returns the elements published so far.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // SUCCESS: no timeout, no error
|
||||
/// func testTimerPublishesIncreasingDates() throws {
|
||||
/// let publisher = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
|
||||
/// let recorder = publisher.record()
|
||||
/// let dates = try wait(for: recorder.availableElements, timeout: ...)
|
||||
/// XCTAssertEqual(dates.sorted(), dates)
|
||||
/// }
|
||||
public var availableElements: PublisherExpectations.AvailableElements<Input, Failure> {
|
||||
PublisherExpectations.AvailableElements(recorder: self)
|
||||
}
|
||||
|
||||
/// Returns a publisher expectation which waits for the recorded publisher
|
||||
/// to complete.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,626 @@
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
class SharedValueObservationTests: GRDBTestCase {
|
||||
func test_immediate_observationLifetime() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var sharedObservation: SharedValueObservation<Int>? = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate,
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
func test_immediate_observationLifetime_reentrancy() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var sharedObservation: SharedValueObservation<Int>? = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate,
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
do {
|
||||
var value1: Int?
|
||||
var value2: Int?
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
value1 = value
|
||||
_ = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
value2 = value
|
||||
})
|
||||
})
|
||||
|
||||
XCTAssertEqual(value1, 0)
|
||||
XCTAssertEqual(value2, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
func test_immediate_publisher() throws {
|
||||
guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else {
|
||||
throw XCTSkip("Combine is not available")
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let publisher = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate)
|
||||
.publisher()
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
try XCTAssertEqual(recorder.next().get(), 0)
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
}
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
try XCTAssertEqual(recorder.next().get(), 1)
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 2)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func test_immediate_whileObserved() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var sharedObservation: SharedValueObservation<Int>? = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate,
|
||||
extent: .whileObserved)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
do {
|
||||
var value: Int?
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value = $0 })
|
||||
|
||||
XCTAssertEqual(value, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
func test_immediate_whileObserved_reentrancy() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var sharedObservation: SharedValueObservation<Int>? = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate,
|
||||
extent: .whileObserved)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
do {
|
||||
var value1: Int?
|
||||
var value2: Int?
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
value1 = value
|
||||
_ = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
value2 = value
|
||||
})
|
||||
})
|
||||
|
||||
XCTAssertEqual(value1, 0)
|
||||
XCTAssertEqual(value2, 0)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
func test_async_observationLifetime() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var sharedObservation: SharedValueObservation<Int>? = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 1
|
||||
var values1: [Int] = []
|
||||
let exp1 = expectation(description: "")
|
||||
exp1.expectedFulfillmentCount = 2
|
||||
exp1.assertForOverFulfill = false
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values1.append($0)
|
||||
exp1.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp1], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1])
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"database did change", "fetch", "value: 1"])
|
||||
|
||||
// --- Start observation 2
|
||||
var values2: [Int] = []
|
||||
let exp2 = expectation(description: "")
|
||||
exp2.expectedFulfillmentCount = 2
|
||||
exp2.assertForOverFulfill = false
|
||||
let cancellable2 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values2.append($0)
|
||||
exp2.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp2], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
|
||||
|
||||
// --- Stop observation 1
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 3
|
||||
var values3: [Int] = []
|
||||
let exp3 = expectation(description: "")
|
||||
exp3.expectedFulfillmentCount = 2
|
||||
exp3.assertForOverFulfill = false
|
||||
let cancellable3 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values3.append($0)
|
||||
exp3.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp3], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2, 3])
|
||||
XCTAssertEqual(values3, [2, 3])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"])
|
||||
|
||||
// --- Stop observation 2
|
||||
cancellable2.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Stop observation 3
|
||||
cancellable3.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Release shared observation
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
func test_async_observationLifetime_early_release() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var sharedObservation: SharedValueObservation<Int>? = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
extent: .observationLifetime)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// ---
|
||||
let exp = expectation(description: "")
|
||||
exp.expectedFulfillmentCount = 3
|
||||
let cancellable = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: { value in
|
||||
// Early release
|
||||
sharedObservation = nil
|
||||
|
||||
switch value {
|
||||
case 0:
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 0", "tracked region: player(*)"])
|
||||
case 1:
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 1"])
|
||||
case 2:
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
exp.fulfill()
|
||||
|
||||
try! dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
})
|
||||
|
||||
wait(for: [exp], timeout: 1)
|
||||
log.flush() // Ignore eventual notification of value: 3
|
||||
|
||||
cancellable.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
func test_async_publisher() throws {
|
||||
guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else {
|
||||
throw XCTSkip("Combine is not available")
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let publisher = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.shared(in: dbQueue) // default async
|
||||
.publisher()
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
try XCTAssert(recorder.availableElements.get().isEmpty)
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 0)
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
}
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
try XCTAssert(recorder.availableElements.get().isEmpty)
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 2)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func test_async_whileObserved() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var sharedObservation: SharedValueObservation<Int>? = ValueObservation
|
||||
.tracking(Table("player").fetchCount)
|
||||
.print(to: log)
|
||||
.shared(
|
||||
in: dbQueue,
|
||||
scheduling: .async(onQueue: .main),
|
||||
extent: .whileObserved)
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 1
|
||||
var values1: [Int] = []
|
||||
let exp1 = expectation(description: "")
|
||||
exp1.expectedFulfillmentCount = 2
|
||||
exp1.assertForOverFulfill = false
|
||||
let cancellable1 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values1.append($0)
|
||||
exp1.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp1], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1])
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"database did change", "fetch", "value: 1"])
|
||||
|
||||
// --- Start observation 2
|
||||
var values2: [Int] = []
|
||||
let exp2 = expectation(description: "")
|
||||
exp2.expectedFulfillmentCount = 2
|
||||
exp2.assertForOverFulfill = false
|
||||
let cancellable2 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values2.append($0)
|
||||
exp2.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp2], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
|
||||
|
||||
// --- Stop observation 1
|
||||
cancellable1.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Start observation 3
|
||||
var values3: [Int] = []
|
||||
let exp3 = expectation(description: "")
|
||||
exp3.expectedFulfillmentCount = 2
|
||||
exp3.assertForOverFulfill = false
|
||||
let cancellable3 = sharedObservation!.start(
|
||||
onError: { XCTFail("Unexpected error \($0)") },
|
||||
onChange: {
|
||||
values3.append($0)
|
||||
exp3.fulfill()
|
||||
})
|
||||
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
wait(for: [exp3], timeout: 1)
|
||||
XCTAssertEqual(values1, [0, 1, 2])
|
||||
XCTAssertEqual(values2, [1, 2, 3])
|
||||
XCTAssertEqual(values3, [2, 3])
|
||||
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"])
|
||||
|
||||
// --- Stop observation 2
|
||||
cancellable2.cancel()
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
|
||||
// --- Stop observation 3
|
||||
cancellable3.cancel()
|
||||
XCTAssertEqual(log.flush(), ["cancel"])
|
||||
|
||||
// --- Release shared observation
|
||||
sharedObservation = nil
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
func test_error_recovery_observationLifetime() throws {
|
||||
guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else {
|
||||
throw XCTSkip("Combine is not available")
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var fetchError: Error? = nil
|
||||
let publisher = ValueObservation
|
||||
.tracking { db -> Int in
|
||||
if let error = fetchError { throw error }
|
||||
return try Table("player").fetchCount(db)
|
||||
}
|
||||
.print(to: log)
|
||||
.shared(in: dbQueue, extent: .observationLifetime)
|
||||
.publisher()
|
||||
|
||||
do {
|
||||
let recorder1 = publisher.record()
|
||||
let recorder2 = publisher.record()
|
||||
|
||||
try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0)
|
||||
try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0)
|
||||
|
||||
fetchError = TestError()
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
|
||||
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
if case .finished = try wait(for: recorder2.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"database did change", "fetch", "failure: TestError()"])
|
||||
}
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
|
||||
do {
|
||||
fetchError = nil
|
||||
let recorder = publisher.record()
|
||||
if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), [])
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Combine)
|
||||
func test_error_recovery_whileObserved() throws {
|
||||
guard #available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) else {
|
||||
throw XCTSkip("Combine is not available")
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
|
||||
let log = Log()
|
||||
var fetchError: Error? = nil
|
||||
let publisher = ValueObservation
|
||||
.tracking { db -> Int in
|
||||
if let error = fetchError { throw error }
|
||||
return try Table("player").fetchCount(db)
|
||||
}
|
||||
.print(to: log)
|
||||
.shared(in: dbQueue, extent: .whileObserved)
|
||||
.publisher()
|
||||
|
||||
do {
|
||||
let recorder1 = publisher.record()
|
||||
let recorder2 = publisher.record()
|
||||
|
||||
try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0)
|
||||
try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0)
|
||||
|
||||
fetchError = TestError()
|
||||
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
|
||||
|
||||
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
if case .finished = try wait(for: recorder2.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), [
|
||||
"start", "fetch", "value: 0", "tracked region: player(*)",
|
||||
"database did change", "fetch", "failure: TestError()"])
|
||||
}
|
||||
|
||||
do {
|
||||
let recorder = publisher.record()
|
||||
if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") }
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "failure: TestError()"])
|
||||
}
|
||||
|
||||
do {
|
||||
fetchError = nil
|
||||
let recorder = publisher.record()
|
||||
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
|
||||
XCTAssertEqual(log.flush(), ["start", "fetch", "value: 1", "tracked region: player(*)"])
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
private class Log: TextOutputStream {
|
||||
var strings: [String] = []
|
||||
let lock = NSLock()
|
||||
|
||||
func write(_ string: String) {
|
||||
lock.lock()
|
||||
strings.append(string)
|
||||
lock.unlock()
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func flush() -> [String] {
|
||||
lock.lock()
|
||||
let result = strings
|
||||
strings = []
|
||||
lock.unlock()
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
private struct TestError: Error { }
|
||||
@@ -356,8 +356,11 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
func testExistsIdentifiable() throws {
|
||||
guard #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) else {
|
||||
throw XCTSkip("Identifiable is not available")
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inTransaction { db in
|
||||
struct Player: TableRecord, Identifiable {
|
||||
|
||||
Reference in new issue
Block a user