Skip to content

Instantly share code, notes, and snippets.

@tonyarnold
Created September 11, 2020 05:52
Show Gist options
  • Save tonyarnold/1535079d749431e9bccd197cb133e5f4 to your computer and use it in GitHub Desktop.
Save tonyarnold/1535079d749431e9bccd197cb133e5f4 to your computer and use it in GitHub Desktop.
Experiment to implement bidirectional assignment of values using Combine/KVO publishers
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