diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index ca694be0d..4dc901253 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -620,16 +620,16 @@ extension DatabaseReader { } return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ }) } else { - var isCancelled = false + let cancellable = AnyDatabaseCancellable() asyncRead { dbResult in - guard !isCancelled else { return } + if cancellable.isCancelled { return } let result = dbResult.flatMap { db in Result { try observation.fetchInitialValue(db) } } scheduler.schedule { - guard !isCancelled else { return } + if cancellable.isCancelled { return } do { try onChange(result.get()) } catch { @@ -637,7 +637,7 @@ extension DatabaseReader { } } } - return AnyDatabaseCancellable(cancel: { isCancelled = true }) + return cancellable } } } diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 242214bc4..c3ba4486a 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -89,16 +89,16 @@ extension DatabaseRegionObservation { onChange: @escaping (Database) -> Void) -> AnyDatabaseCancellable { - @LockedBox var state = ObservationState.pending + let stateMutex = LockedBox(wrappedValue: ObservationState.pending) // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. writer.unsafeReentrantWrite { db in do { let region = try observedRegion(db).observableRegion(db) - $state.update { + stateMutex.update { state in let observer = DatabaseRegionObserver(region: region, onChange: { - if case .cancelled = state { + if case .cancelled = stateMutex.wrappedValue { return } onChange($0) @@ -111,7 +111,7 @@ extension DatabaseRegionObservation { // the observer. db.add(transactionObserver: observer, extent: .observerLifetime) - $0 = .started(observer) + state = .started(observer) } } catch { onError(error) @@ -122,7 +122,7 @@ extension DatabaseRegionObservation { // Deallocates the transaction observer. This makes sure that the // `onChange` callback will never be called again, because the // observation was started with the `.observerLifetime` extent. - state = .cancelled + stateMutex.wrappedValue = .cancelled } } } diff --git a/GRDB/ValueObservation/DatabaseCancellable.swift b/GRDB/ValueObservation/DatabaseCancellable.swift index de6298791..0eb8d0f79 100644 --- a/GRDB/ValueObservation/DatabaseCancellable.swift +++ b/GRDB/ValueObservation/DatabaseCancellable.swift @@ -1,3 +1,5 @@ +import Foundation + /// A protocol indicating that an activity or action supports cancellation. /// /// ## Topics @@ -5,7 +7,7 @@ /// ### Supporting Types /// /// - ``AnyDatabaseCancellable`` -public protocol DatabaseCancellable { +public protocol DatabaseCancellable: Sendable { /// Cancel the activity. func cancel() } @@ -15,31 +17,40 @@ public protocol DatabaseCancellable { /// /// An `AnyDatabaseCancellable` instance automatically calls ``cancel()`` /// when deinitialized. -public class AnyDatabaseCancellable: DatabaseCancellable { - private var _cancel: (() -> Void)? +public final class AnyDatabaseCancellable: DatabaseCancellable, @unchecked Sendable { + // @unchecked Sendable due to `_cancel`, which is protected by `lock`. + private let lock = NSLock() + private var _cancel: (@Sendable () -> Void)? + + var isCancelled: Bool { + lock.withLock { _cancel == nil } + } + + convenience init() { + self.init(cancel: { }) + } /// Initializes the cancellable object with the given cancel-time closure. - public init(cancel: @escaping () -> Void) { + public init(cancel: @escaping @Sendable () -> Void) { _cancel = cancel } /// Creates a cancellable object that forwards cancellation to `base`. public convenience init(_ base: some DatabaseCancellable) { - var cancellable = Optional.some(base) self.init { - cancellable?.cancel() - cancellable = nil // Release memory + base.cancel() } } deinit { - _cancel?() + cancel() } public func cancel() { - // Don't prevent multiple concurrent calls to _cancel, because it is - // pointless. But release memory! - _cancel?() + lock.lock() + let cancel = _cancel _cancel = nil + lock.unlock() + cancel?() } } diff --git a/TODO.md b/TODO.md index f0d4a88e8..3ad01c3eb 100644 --- a/TODO.md +++ b/TODO.md @@ -96,7 +96,7 @@ - [ ] GRDB7: Consider putting a Task cancellation handler on async methods. - [X] GRDB7: All writes should be immediate, right? https://github.com/groue/GRDB.swift/pull/1485#issuecomment-1953793553 - [ ] GRDB7: Sendable conformances - - [ ] anydatabasecancellable + - [X] anydatabasecancellable - [ ] anydatabaseregionconvertible - [ ] anyfetchrequest - [ ] anysqljsonexpressible