From 9e0b1b3ded90375824788508312394a2a304665d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 23 Oct 2021 16:24:42 +0200 Subject: [PATCH 01/16] SharedValueObservation --- GRDB.xcodeproj/project.pbxproj | 18 + .../SharedValueObservation.swift | 152 ++++++ .../ValueObservationScheduler.swift | 8 + GRDBCustom.xcodeproj/project.pbxproj | 12 + .../SharedValueObservationTests.swift | 440 ++++++++++++++++++ 5 files changed, 630 insertions(+) create mode 100644 GRDB/ValueObservation/SharedValueObservation.swift create mode 100644 Tests/GRDBTests/SharedValueObservationTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b368c7d9c..6d1db28ad 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -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 */; }; @@ -1258,6 +1265,8 @@ /* Begin PBXFileReference section */ 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; + 560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; + 560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -1791,6 +1800,7 @@ isa = PBXGroup; children = ( 563082E32430B6BE00C14A05 /* DatabaseCancellable.swift */, + 560233C32724234F00529DF3 /* SharedValueObservation.swift */, 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */, 564CE43021AA901800652B19 /* ValueObserver.swift */, @@ -1933,6 +1943,7 @@ 563B06BF2185CD1700B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 560233C82724338800529DF3 /* SharedValueObservationTests.swift */, 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */, 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */, @@ -2943,6 +2954,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 +3142,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 */, @@ -3368,6 +3381,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 */, @@ -3600,6 +3614,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 +3742,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 */, @@ -3965,6 +3981,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 +4109,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 */, diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift new file mode 100644 index 000000000..2e3d11ca3 --- /dev/null +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -0,0 +1,152 @@ +import Foundation + +public enum SharedValueObservationExtent { + case observationLifetime + case whileObserved +} + +extension ValueObservation { + public func shared( + in reader: DatabaseReader, + scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), + extent: SharedValueObservationExtent) + -> SharedValueObservation + { + SharedValueObservation(scheduling: scheduler, extent: extent) { onError, onChange in + self.start(in: reader, scheduling: scheduler, onError: onError, onChange: onChange) + } + } +} + +public final class SharedValueObservation { + typealias StartFunction = ( + _ onError: @escaping (Error) -> Void, + _ onChange: @escaping (Element) -> Void) + -> DatabaseCancellable + + private let scheduler: ValueObservationScheduler + private let extent: SharedValueObservationExtent + private let startObservation: StartFunction + 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? + + 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 StartFunction) + { + self.scheduler = scheduler + self.extent = extent + self.startObservation = startObservation + self.clients = [] + } + + 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) + } + } + } + + private func handleError(_ error: Error) { + synchronized { + let notifiedClients = clients + + // State change + lastResult = .failure(error) + clients = [] + + // 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 + } + } + } + + private func synchronized(_ execute: () throws -> T) rethrows -> T { + lock.lock() + defer { lock.unlock() } + return try execute() + } +} diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index cc8036f46..61cce1d97 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -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 { diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index fd61db0aa..4fbaf6473 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -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 */; }; @@ -768,6 +772,8 @@ /* Begin PBXFileReference section */ 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; + 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; + 560233D027243A9100529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; @@ -1265,6 +1271,7 @@ isa = PBXGroup; children = ( 563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */, + 560233D027243A9100529DF3 /* SharedValueObservation.swift */, 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, 563A4B6F242E7CE50075D8CF /* ValueObservationScheduler.swift */, 564CE43B21AA955B00652B19 /* ValueObserver.swift */, @@ -1404,6 +1411,7 @@ 563B06DB2185E04E00B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */, 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */, 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */, @@ -2362,6 +2370,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 +2502,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 */, @@ -2726,6 +2736,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 +2868,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 */, diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift new file mode 100644 index 000000000..812962a77 --- /dev/null +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -0,0 +1,440 @@ +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? = 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? = 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"]) + } + + 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? = 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? = 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? = 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? = 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"]) + } + + 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? = 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(), []) + } +} + +fileprivate 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 + } +} From 8ccaf59d4d893c747e7441a0f9543de804489c02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 23 Oct 2021 17:47:12 +0200 Subject: [PATCH 02/16] Default SharedValueObservation extent: .whileObserved --- GRDB/ValueObservation/SharedValueObservation.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 2e3d11ca3..eded84697 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -9,7 +9,7 @@ extension ValueObservation { public func shared( in reader: DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), - extent: SharedValueObservationExtent) + extent: SharedValueObservationExtent = .whileObserved) -> SharedValueObservation { SharedValueObservation(scheduling: scheduler, extent: extent) { onError, onChange in From a3a804fa8231f567eab3205bc3a70f8f5dabac5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 12:35:31 +0200 Subject: [PATCH 03/16] Upgrade CombineExpectations --- GRDB.xcodeproj/project.pbxproj | 8 +++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++ .../PublisherExpectation.swift | 17 ++++- .../AvailableElements.swift | 62 +++++++++++++++++++ Tests/CombineExpectations/Recorder.swift | 33 ++++++++-- 5 files changed, 121 insertions(+), 5 deletions(-) create mode 100644 Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 6d1db28ad..94d433eb1 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -580,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 */; }; @@ -1487,6 +1490,7 @@ 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; 56915781231BF28B00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = ""; }; + 5691D96927256C3A0021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 569530FB1C9067CC00CF1A2B /* DatabaseQueueCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueCrashTests.swift; sourceTree = ""; }; 569530FC1C9067CC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleCrashTests.swift; sourceTree = ""; }; 569530FD1C9067CC00CF1A2B /* GRDBCrashTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBCrashTestCase.swift; sourceTree = ""; }; @@ -1975,6 +1979,7 @@ 56419A6024A51601004967E1 /* PublisherExpectations */ = { isa = PBXGroup; children = ( + 5691D96927256C3A0021D540 /* AvailableElements.swift */, 56419A6124A51601004967E1 /* Finished.swift */, 56419A6224A51601004967E1 /* NextOne.swift */, 56419A6324A51601004967E1 /* Next.swift */, @@ -3224,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 */, @@ -3457,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 */, @@ -3824,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 */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 4fbaf6473..2927caaa9 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -384,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 */; }; @@ -998,6 +1000,7 @@ 5690C33F1D23E82A00E59934 /* Data.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Data.swift; sourceTree = ""; }; 5691578B231BF2BE00E1D237 /* PoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PoolTests.swift; sourceTree = ""; }; 569178451CED9B6000E179EA /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = ""; }; + 5691D96D27256C490021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaCache.swift; sourceTree = ""; }; 569531231C90878D00CF1A2B /* DatabaseQueueSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueSchemaCacheTests.swift; sourceTree = ""; }; 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolSchemaCacheTests.swift; sourceTree = ""; }; @@ -1455,6 +1458,7 @@ 56419A7924A51614004967E1 /* PublisherExpectations */ = { isa = PBXGroup; children = ( + 5691D96D27256C490021D540 /* AvailableElements.swift */, 56419A7A24A51614004967E1 /* Finished.swift */, 56419A7B24A51614004967E1 /* NextOne.swift */, 56419A7C24A51614004967E1 /* Next.swift */, @@ -2524,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 */, @@ -2890,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 */, diff --git a/Tests/CombineExpectations/PublisherExpectation.swift b/Tests/CombineExpectations/PublisherExpectation.swift index 774511c7e..b8fca0b5a 100644 --- a/Tests/CombineExpectations/PublisherExpectation.swift +++ b/Tests/CombineExpectations/PublisherExpectation.swift @@ -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() } } diff --git a/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift b/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift new file mode 100644 index 000000000..82947bcca --- /dev/null +++ b/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift @@ -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: PublisherExpectation { + let recorder: Recorder + + 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 diff --git a/Tests/CombineExpectations/Recorder.swift b/Tests/CombineExpectations/Recorder.swift index 6120d2415..6b91f405c 100644 --- a/Tests/CombineExpectations/Recorder.swift +++ b/Tests/CombineExpectations/Recorder.swift @@ -277,21 +277,46 @@ public class Recorder: 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 = Map, Subscribers.Completion> - /// The type of the publisher expectation returned by Recorder.elements + /// The type of the publisher expectation returned by `Recorder.elements`. public typealias Elements = Map, [Input]> - /// The type of the publisher expectation returned by Recorder.last + /// The type of the publisher expectation returned by `Recorder.last`. public typealias Last = Map, Input?> - /// The type of the publisher expectation returned by Recorder.single + /// The type of the publisher expectation returned by `Recorder.single`. public typealias Single = Map, 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 { + PublisherExpectations.AvailableElements(recorder: self) + } + /// Returns a publisher expectation which waits for the recorded publisher /// to complete. /// From c3618e0cf038d405ccfda4ff257bf246b03b9e8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 12:38:00 +0200 Subject: [PATCH 04/16] SharedValueObservation publisher --- .../SharedValueObservation.swift | 18 +++-- GRDB/ValueObservation/ValueObservation.swift | 44 ++++++------- .../SharedValueObservationTests.swift | 66 +++++++++++++++++++ 3 files changed, 97 insertions(+), 31 deletions(-) diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index eded84697..cc37c8a1b 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -19,14 +19,9 @@ extension ValueObservation { } public final class SharedValueObservation { - typealias StartFunction = ( - _ onError: @escaping (Error) -> Void, - _ onChange: @escaping (Element) -> Void) - -> DatabaseCancellable - private let scheduler: ValueObservationScheduler private let extent: SharedValueObservationExtent - private let startObservation: StartFunction + private let startObservation: ValueObservationStart private let lock = NSRecursiveLock() // support synchronous observation events // protected by lock @@ -48,7 +43,7 @@ public final class SharedValueObservation { fileprivate init( scheduling scheduler: ValueObservationScheduler, extent: SharedValueObservationExtent, - startObservation: @escaping StartFunction) + startObservation: @escaping ValueObservationStart) { self.scheduler = scheduler self.extent = extent @@ -106,6 +101,15 @@ public final class SharedValueObservation { } } +#if canImport(Combine) + @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + public func publisher() -> DatabasePublishers.Value { + DatabasePublishers.Value { onError, onChange in + self.start(onError: onError, onChange: onChange) + } + } +#endif + private func handleError(_ error: Error) { synchronized { let notifiedClients = clients diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 86e6f89e5..d3e6bfe2b 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -52,6 +52,11 @@ struct ValueObservationEvents: Refinable { var didCancel: (() -> Void)? } +typealias ValueObservationStart = ( + _ onError: @escaping (Error) -> Void, + _ onChange: @escaping (T) -> Void) +-> DatabaseCancellable + extension ValueObservation: Refinable { // MARK: - Starting Observation @@ -261,39 +266,30 @@ extension ValueObservation { scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main)) -> DatabasePublishers.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 = ( - _ 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: Publisher { public typealias Failure = Error - private let start: Start + private let start: ValueObservationStart - init( - _ observation: ValueObservation, - 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) { + self.start = start } public func receive(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input { @@ -309,7 +305,7 @@ extension DatabasePublishers { { private struct WaitingForDemand { let downstream: Downstream - let start: Start + let start: ValueObservationStart } private struct Observing { @@ -336,7 +332,7 @@ extension DatabasePublishers { private var lock = NSRecursiveLock() // Allow re-entrancy init( - start: @escaping Start, + start: @escaping ValueObservationStart, downstream: Downstream) { state = .waitingForDemand(WaitingForDemand( diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index 812962a77..d16272ea5 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -94,6 +94,39 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(log.flush(), ["cancel"]) } +#if canImport(Combine) + @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + func test_immediate_publisher() throws { + 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 @@ -326,7 +359,40 @@ class SharedValueObservationTests: GRDBTestCase { cancellable.cancel() XCTAssertEqual(log.flush(), ["cancel"]) } + +#if canImport(Combine) + @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) + func test_async_publisher() throws { + 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 From a5dd61ff1366bb7872d95ce20f852c3b625b29ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 13:17:43 +0200 Subject: [PATCH 05/16] Fix availability checks in tests Fix `make test_framework_GRDBiOS_minTarget` with Xcode 13 --- Tests/GRDBTests/SharedValueObservationTests.swift | 10 ++++++++-- .../TableRecord+QueryInterfaceRequestTests.swift | 5 ++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index d16272ea5..d4be5ad2e 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -95,8 +95,11 @@ class SharedValueObservationTests: GRDBTestCase { } #if canImport(Combine) - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) 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 @@ -361,8 +364,11 @@ class SharedValueObservationTests: GRDBTestCase { } #if canImport(Combine) - @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) 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 diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index 91e481720..9277b99ce 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -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 { From 450ff6239299a40f8206dc13382c5f2c43d1192f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 14:03:39 +0200 Subject: [PATCH 06/16] Fix SQLCipher tests --- .../SQLCipher3/GRDBTests.xcodeproj/project.pbxproj | 6 ++++++ .../SQLCipher4/GRDBTests.xcodeproj/project.pbxproj | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 45a096adb..7adce2aec 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -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 = ""; }; 564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 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 = ""; }; 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 = ""; }; 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 = ""; }; @@ -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 */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index e62fc8a7f..61f62b11b 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -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 = ""; }; 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 = ""; }; 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 = ""; }; 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 */, From abc6c55e1404e65df047eb0746a92046b7716c0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 15:17:52 +0200 Subject: [PATCH 07/16] Documentation --- .../SharedValueObservation.swift | 121 ++++++++++++++++++ GRDB/ValueObservation/ValueObservation.swift | 3 + 2 files changed, 124 insertions(+) diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index cc37c8a1b..2d1d76d73 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -1,11 +1,69 @@ 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. + /// + /// Note that this extent prevents the observation from recovering from + /// database errors. case observationLifetime + + /// The `SharedValueObservation` ends database observation when the number + /// of subscriptions drops down to zero. 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 = observation.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. + /// + /// - 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), @@ -18,6 +76,32 @@ extension ValueObservation { } } +/// 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 { private let scheduler: ValueObservationScheduler private let extent: SharedValueObservationExtent @@ -51,6 +135,27 @@ public final class SharedValueObservation { 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) @@ -102,6 +207,22 @@ public final class SharedValueObservation { } #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 { DatabasePublishers.Value { onError, onChange in diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index d3e6bfe2b..fe2e5339f 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -95,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. From 2f212b8a5fc399a064bb8a4bb3ed33629c71e45c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 15:46:32 +0200 Subject: [PATCH 08/16] SharedValueObservation error handling --- .../SharedValueObservation.swift | 20 ++- .../SharedValueObservationTests.swift | 116 +++++++++++++++++- 2 files changed, 131 insertions(+), 5 deletions(-) diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 2d1d76d73..d855d2056 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -7,12 +7,17 @@ public enum SharedValueObservationExtent { /// ends when the `SharedValueObservation` is deallocated and all /// subscriptions terminated. /// - /// Note that this extent prevents the observation from recovering from - /// database errors. + /// 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. + /// 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 } @@ -236,8 +241,14 @@ public final class SharedValueObservation { let notifiedClients = clients // State change - lastResult = .failure(error) clients = [] + if extent == .whileObserved { + isObserving = false + cancellable = nil + lastResult = nil + } else { + lastResult = .failure(error) + } // Side effect for client in notifiedClients { @@ -265,6 +276,7 @@ public final class SharedValueObservation { if clients.isEmpty && extent == .whileObserved { isObserving = false cancellable = nil + lastResult = nil } } } diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index d4be5ad2e..8d24ccd2d 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -489,9 +489,121 @@ class SharedValueObservationTests: GRDBTestCase { 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 } -fileprivate class Log: TextOutputStream { +private class Log: TextOutputStream { var strings: [String] = [] let lock = NSLock() @@ -510,3 +622,5 @@ fileprivate class Log: TextOutputStream { return result } } + +private struct TestError: Error { } From 7690db9284ba19888388fe06ddb5fd76323d8b24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 16:15:46 +0200 Subject: [PATCH 09/16] Documentation --- Documentation/Combine.md | 19 +++++ .../SharedValueObservation.swift | 13 ++- README.md | 83 ++++++++++++++++--- 3 files changed, 102 insertions(+), 13 deletions(-) diff --git a/Documentation/Combine.md b/Documentation/Combine.md index b83f71835..cec1d4d7c 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -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(in: dbQueue) +``` + +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 diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index d855d2056..b96de7161 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -50,9 +50,11 @@ extension ValueObservation { /// and the first one is immediately notified when the start() method /// is called: /// - /// let sharedObservation = observation.shared( - /// in: dbQueue, - /// scheduling: .immediate) // <- + /// let sharedObservation = ValueObservation + /// .tracking { db in try Player.fetchAll(db) } + /// .shared( + /// in: dbQueue, + /// scheduling: .immediate) // <- /// /// let cancellable = try sharedObservation.start( /// onError: { error in ... }, @@ -64,6 +66,11 @@ extension ValueObservation { /// 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. diff --git a/README.md b/README.md index ae57aedfd..3a6f4c7da 100644 --- a/README.md +++ b/README.md @@ -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,71 @@ let observation = ValueObservation See also [ValueObservation.handleEvents](#valueobservationhandleevents). +### ValueObservation Sharing + +**Sharing a database observation spares database resources.** + +For example: + +```swift +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) +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``` + + ### ValueObservation Performance This chapter further describes runtime aspects of ValueObservation, and provides some optimization tips for demanding applications. @@ -6168,19 +6234,16 @@ 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. + 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). - For example, with RxSwift and RxGRDB, you can use the `share(replay:scope:)` operator: + For example: ```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) + let observation = ValueObservation.tracking { db in ... } + let sharedObservation = observation.shared(in: dbQueue) + let cancellable = sharedObservation.start( + onError: { error in ... }, + onChange: { value in print("fresh value") }) ``` 3. :bulb: **Tip**: Use a [database pool](#database-pools), because it can perform multi-threaded database accesses. From c62e4fd94c8e7fac33d65ba25f5da3c37ce38bd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 16:17:46 +0200 Subject: [PATCH 10/16] Documentation --- README.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/README.md b/README.md index 3a6f4c7da..db1c4998a 100644 --- a/README.md +++ b/README.md @@ -6235,16 +6235,6 @@ When needed, you can help GRDB optimize observations and reduce database content 2. :bulb: **Tip**: Share observations when possible. 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). - - For example: - - ```swift - let observation = ValueObservation.tracking { db in ... } - let sharedObservation = observation.shared(in: dbQueue) - let cancellable = sharedObservation.start( - onError: { error in ... }, - onChange: { value in print("fresh value") }) - ``` 3. :bulb: **Tip**: Use a [database pool](#database-pools), because it can perform multi-threaded database accesses. From ae0edde7c5f5fd0f6283252d7334bceca0720367 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 16:22:47 +0200 Subject: [PATCH 11/16] Documentation --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index db1c4998a..ef620b43b 100644 --- a/README.md +++ b/README.md @@ -6154,6 +6154,7 @@ See also [ValueObservation.handleEvents](#valueobservationhandleevents). For example: ```swift +// SharedValueObservation<[Player]> let sharedObservation = ValueObservation .tracking { db in try Player.fetchAll(db) } .shared(in: dbQueue) From 22a4f08f406c156f83198b4470eb9ab6723b3a39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 16:25:18 +0200 Subject: [PATCH 12/16] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ee093c46..81db9ae92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 From 76cac4572086857f776e4c336e07cfc7c74078ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 16:35:32 +0200 Subject: [PATCH 13/16] Fix typo --- Documentation/Combine.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/Combine.md b/Documentation/Combine.md index cec1d4d7c..990d1fe4c 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -261,7 +261,7 @@ let sharedObservation = ValueObservation .shared(in: dbQueue) // A publisher with output [Player] and failure Error -let publisher = sharedObservation.publisher(in: dbQueue) +let publisher = sharedObservation.publisher() ``` This publisher has the same behavior as SharedValueObservation. From d73228a8129c26705639a94247c8f9d524722ba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 17:04:07 +0200 Subject: [PATCH 14/16] Documentation --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index ef620b43b..8452c6f66 100644 --- a/README.md +++ b/README.md @@ -6212,6 +6212,20 @@ let sharedObservation = ValueObservation // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` +> :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 connectionn won't close. + ### ValueObservation Performance From 909afc0233dbb7cfbd1ea340d1631bce3df62267 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 17:05:10 +0200 Subject: [PATCH 15/16] Fix typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8452c6f66..102160d7b 100644 --- a/README.md +++ b/README.md @@ -6215,8 +6215,8 @@ let sharedObservation = ValueObservation > :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` +> +> ```swift > let sharedObservation = ValueObservation.tracking { ... }.shared(in: dbQueue) > let cancellable = try sharedObservation > .publisher() // Turn shared observation into a Combine Publisher From 92e4c8f785beb3d951a72fab1f949ac26bb56591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 24 Oct 2021 17:06:25 +0200 Subject: [PATCH 16/16] I want a new keyboard ASAP --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 102160d7b..3edd11045 100644 --- a/README.md +++ b/README.md @@ -6224,7 +6224,7 @@ let sharedObservation = ValueObservation > .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 connectionn won't close. +> - 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