diff --git a/Package.swift b/Package.swift index 5fc29c0..fe421ee 100644 --- a/Package.swift +++ b/Package.swift @@ -5,7 +5,7 @@ import PackageDescription let package = Package( name: "UserDefaultsSnapshotLib", - platforms: [.iOS(.v12)], + platforms: [.iOS(.v13)], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( diff --git a/Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStore.swift b/Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStore.swift index 58ee545..3365090 100644 --- a/Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStore.swift +++ b/Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStore.swift @@ -55,11 +55,10 @@ open class UserDefaultsPersistentStore: UserDefaults } } - public final func sinkSnapshot(_ sink: @escaping (UserDefaultsSnapshot) -> Void) -> UserDefaultsPersistentStoreSinkCancellable { + public final func sinkSnapshot(_ sink: @escaping @Sendable (UserDefaultsSnapshot) -> Void) -> UserDefaultsPersistentStoreSinkCancellable { - let token = UserDefaultsPersistentStoreSinkCancellable(owner: self) - - initial: do { + // deliver initial + do { let snapshot = makeSnapshot() sink( @@ -67,20 +66,51 @@ open class UserDefaultsPersistentStore: UserDefaults ) } - add { [weak self] in + return add { [weak self] in guard let self = self else { return } let snapshot = self.makeSnapshot() - DispatchQueue.main.async { + sink( + snapshot + ) + } + + } + + public final func sinkSnapshotOnMain(_ sink: @escaping @MainActor (UserDefaultsSnapshot) -> Void) -> UserDefaultsPersistentStoreSinkCancellable { + + // deliver initial + do { + let snapshot = makeSnapshot() + + if Thread.isMainThread { + MainActor.assumeIsolated { + sink( + snapshot + ) + } + } else { + Task { @MainActor in + sink( + snapshot + ) + } + } + } + + return add { [weak self] in + guard let self = self else { return } + + let snapshot = self.makeSnapshot() + + Task { @MainActor in sink( snapshot ) } } - return token - } } diff --git a/Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStoreBase.swift b/Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStoreBase.swift index 778cddb..e86c13e 100644 --- a/Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStoreBase.swift +++ b/Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStoreBase.swift @@ -16,7 +16,6 @@ open class UserDefaultsPersistentStoreBase: @unchecked Sendable { private let lock = NSLock() - @discardableResult public func add(_ eventReceiver: @escaping () -> Void) -> UserDefaultsPersistentStoreSinkCancellable { let token = UserDefaultsPersistentStoreSinkCancellable(owner: self) lock.lock()