AsyncMonitor/Sources/AsyncMonitor/NSObject+AsyncKVO.swift
2025-04-25 16:23:53 -07:00

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