Skip to content

Commit

Permalink
Added KVO support via NSObject.currentValuePublisher(for:)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukaskubanek committed Jan 29, 2025
1 parent 26beaa5 commit 5c20b7f
Showing 1 changed file with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Foundation

public protocol KVOCurrentValuePublishing {}

extension NSObject: KVOCurrentValuePublishing {}

extension KVOCurrentValuePublishing where Self: NSObject {

/// Returns a `CurrentValuePublisher` that tracks the current value of a KVO-compliant property.
///
/// - Parameter keyPath: The key path of the property to observe.
/// - Returns: A `CurrentValuePublisher` that tracks the property's value.
///
/// This implementation follows the approach of `NSObject.publisher(for:options:)` from Foundation,
/// previously available in the [swift-corelibs-foundation](https://bit.ly/nsobject-keyvalueobserving)
/// open source repository.
public func currentValuePublisher<Value>(
for keyPath: KeyPath<Self, Value>
) -> CurrentValuePublisher<Value, Never> {
return CurrentValuePublisher(
initial: self[keyPath: keyPath],
upstream: self.publisher(for: keyPath, options: .new)
)
}

}

0 comments on commit 5c20b7f

Please sign in to comment.