extension NSObjectProtocol where Self: NSObject { func observe<T>(keyPath: KeyPath<Self, T>) -> AsyncStream<T> { AsyncStream { continuation in let observation = self.observe(keyPath, options: [.new]) { _, change in if let newValue = change.newValue { continuation.yield(newValue) } } continuation.onTermination = { @Sendable _ in print("onTermination") observation.invalidate() } } } }
こういうの生やして実験してみたけど