Skip to content

Commit

Permalink
Patch
Browse files Browse the repository at this point in the history
  • Loading branch information
muukii committed Apr 20, 2024
1 parent 2778214 commit c79b0d2
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 10 deletions.
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
46 changes: 38 additions & 8 deletions Sources/UserDefaultsSnapshotLib/UserDefaultsPersistentStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,32 +55,62 @@ open class UserDefaultsPersistentStore<Schema: UserDefaultsObject>: UserDefaults
}
}

public final func sinkSnapshot(_ sink: @escaping (UserDefaultsSnapshot<Schema>) -> Void) -> UserDefaultsPersistentStoreSinkCancellable {
public final func sinkSnapshot(_ sink: @escaping @Sendable (UserDefaultsSnapshot<Schema>) -> Void) -> UserDefaultsPersistentStoreSinkCancellable {

let token = UserDefaultsPersistentStoreSinkCancellable(owner: self)

initial: do {
// deliver initial
do {
let snapshot = makeSnapshot()

sink(
snapshot
)
}

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<Schema>) -> 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

}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit c79b0d2

Please sign in to comment.