From ec5b7d96e2d4ae2cd0f9d604e2495ce866eaf934 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Sep 2024 15:51:04 +0200 Subject: [PATCH] SharedValueObservation is Sendable --- .../SharedValueObservation.swift | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 1abf6998c..d43e03013 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -167,7 +167,8 @@ extension ValueObservation { /// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) /// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) /// ``` -public final class SharedValueObservation { +public final class SharedValueObservation: @unchecked Sendable { + // @unchecked Sendable because state is protected by `lock`. private let scheduler: any ValueObservationScheduler private let extent: SharedValueObservationExtent private let startObservation: ValueObservationStart @@ -179,9 +180,9 @@ public final class SharedValueObservation { private var cancellable: AnyDatabaseCancellable? private var lastResult: Result? - private final class Client { - var onError: @Sendable (Error) -> Void - var onChange: @Sendable (Element) -> Void + private final class Client: Sendable { + let onError: @Sendable (Error) -> Void + let onChange: @Sendable (Element) -> Void init( onError: @escaping @Sendable (Error) -> Void, @@ -231,7 +232,7 @@ public final class SharedValueObservation { onChange: @escaping @Sendable (Element) -> Void) -> AnyDatabaseCancellable { - synchronized { + withLock { // Support for reentrancy: a shared immediate observation is // started from the first value notification of that same shared // immediate observation. Yeah, users are nasty. @@ -303,7 +304,7 @@ public final class SharedValueObservation { #endif private func handleError(_ error: Error) { - synchronized { + withLock { let notifiedClients = clients // State change @@ -324,7 +325,7 @@ public final class SharedValueObservation { } private func handleChange(_ value: Element) { - synchronized { + withLock { // State change lastResult = .success(value) @@ -336,7 +337,7 @@ public final class SharedValueObservation { } private func handleCancel(_ client: Client) { - synchronized { + withLock { // State change clients.removeFirst(where: { $0 === client }) if clients.isEmpty && extent == .whileObserved { @@ -347,7 +348,7 @@ public final class SharedValueObservation { } } - private func synchronized(_ execute: () throws -> T) rethrows -> T { + private func withLock(_ execute: () throws -> T) rethrows -> T { lock.lock() defer { lock.unlock() } return try execute()