Skip to content

Commit 5c20b7f

Browse files
committed
Added KVO support via NSObject.currentValuePublisher(for:)
1 parent 26beaa5 commit 5c20b7f

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import Foundation
2+
3+
public protocol KVOCurrentValuePublishing {}
4+
5+
extension NSObject: KVOCurrentValuePublishing {}
6+
7+
extension KVOCurrentValuePublishing where Self: NSObject {
8+
9+
/// Returns a `CurrentValuePublisher` that tracks the current value of a KVO-compliant property.
10+
///
11+
/// - Parameter keyPath: The key path of the property to observe.
12+
/// - Returns: A `CurrentValuePublisher` that tracks the property's value.
13+
///
14+
/// This implementation follows the approach of `NSObject.publisher(for:options:)` from Foundation,
15+
/// previously available in the [swift-corelibs-foundation](https://bit.ly/nsobject-keyvalueobserving)
16+
/// open source repository.
17+
public func currentValuePublisher<Value>(
18+
for keyPath: KeyPath<Self, Value>
19+
) -> CurrentValuePublisher<Value, Never> {
20+
return CurrentValuePublisher(
21+
initial: self[keyPath: keyPath],
22+
upstream: self.publisher(for: keyPath, options: .new)
23+
)
24+
}
25+
26+
}

0 commit comments

Comments
 (0)