Forked from tonyarnold/NSObject+BidirectionalAssign.swift
Created
February 9, 2022 15:33
-
-
Save amine2233/d83bac765e5468460fe2da96c8af96c8 to your computer and use it in GitHub Desktop.
Experiment to implement bidirectional assignment of values using Combine/KVO publishers
This file contains 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