Fix a crash when an observation is quickly cancelled

This commit is contained in:
Renaud Lienhart committed 2022-03-31 10:55:00 +11:00
1 parent 9014b3ebd0
commit 80c15c6ef6
1 file changed
+9 -8
@@ -198,7 +198,10 @@ extension ValueWriteOnlyObserver {
// from a database access.
try writer.unsafeReentrantWrite { db in
// Fetch & Start observing the database
let fetchedValue = try fetchAndStartObservation(db)
guard let fetchedValue = try fetchAndStartObservation(db) else {
// Likely a GRDB bug
fatalError("can't start a cancelled or failed observation")
}
// Reduce
return reduceQueue.sync {
@@ -218,12 +221,11 @@ extension ValueWriteOnlyObserver {
// Start from a write access, so that self can register as a
// transaction observer.
writer.asyncWriteWithoutTransaction { db in
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
do {
// Fetch & Start observing the database
let fetchedValue = try self.fetchAndStartObservation(db)
guard let fetchedValue = try self.fetchAndStartObservation(db) else {
return /* Cancelled */
}
// Reduce
//
@@ -260,14 +262,13 @@ extension ValueWriteOnlyObserver {
/// By grouping the initial fetch and the beginning of observation in a
/// single database access, we are sure that no concurrent write can happen
/// during the initial fetch, and that we won't miss any future change.
private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched {
private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched? {
// TODO: [SR-214] remove -Opt suffix when we only support Xcode 12.5.1+
let (eventsOpt, fetchOpt) = lock.synchronized {
(notificationCallbacks?.events, databaseAccess?.fetch)
}
guard let events = eventsOpt, let fetch = fetchOpt else {
// Likely a GRDB bug
fatalError("can't start a cancelled or failed observation")
return nil /* Cancelled */
}
switch trackingMode {