mirror of
https://github.com/samsonjs/AsyncMonitor.git
synced 2026-03-25 08:25:47 +00:00
20 lines
735 B
Swift
20 lines
735 B
Swift
public import Foundation
|
|
|
|
extension KeyPath: @unchecked @retroactive Sendable where Value: Sendable {}
|
|
|
|
public extension NSObjectProtocol where Self: NSObject {
|
|
func values<Value: Sendable>(
|
|
for keyPath: KeyPath<Self, Value>,
|
|
options: NSKeyValueObservingOptions = [],
|
|
changeHandler: @escaping @MainActor (Value) -> Void
|
|
) -> any AsyncCancellable {
|
|
let (stream, continuation) = AsyncStream<Value>.makeStream()
|
|
let token = self.observe(keyPath, options: options) { object, _ in
|
|
continuation.yield(object[keyPath: keyPath])
|
|
}
|
|
return stream.monitor { @MainActor value in
|
|
_ = token // keep this alive
|
|
changeHandler(value)
|
|
}
|
|
}
|
|
}
|