Created
September 11, 2020 05:52
-
-
Save tonyarnold/1535079d749431e9bccd197cb133e5f4 to your computer and use it in GitHub Desktop.
Experiment to implement bidirectional assignment of values using Combine/KVO publishers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Combine | |
import Foundation | |
extension NSObjectProtocol where Self: NSObject { | |
/// Assigns each unique element assigned to the key paths specified to the inverse object. | |
func bidirectionallyAssign<Value: Equatable, B: NSObject>( | |
from firstKeyPath: ReferenceWritableKeyPath<Self, Value>, | |
to secondKeyPath: ReferenceWritableKeyPath<B, Value>, | |
on otherObject: B | |
) -> [AnyCancellable] { | |
return [ | |
publisher(for: firstKeyPath, options: [.initial, .new]) | |
.removeDuplicates() | |
.assign(to: secondKeyPath, on: otherObject), | |
otherObject.publisher(for: secondKeyPath, options: [.new]) | |
.removeDuplicates() | |
.assign(to: firstKeyPath, on: self) | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment