Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save amine2233/d83bac765e5468460fe2da96c8af96c8 to your computer and use it in GitHub Desktop.
Save amine2233/d83bac765e5468460fe2da96c8af96c8 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