Last active
September 23, 2021 13:48
-
-
Save Czajnikowski/4c7100f10fb3d8da22ee17bdbac00e9c to your computer and use it in GitHub Desktop.
Solution for propagating changes from nested ObservableObjects
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
class TrackViewModel { | |
private let nestedViewModel: PlaybackViewModel | |
private var propagation: Any? | |
init(nestedViewModel: PlaybackViewModel) { | |
self.nestedViewModel = nestedViewModel | |
propagation = nestedViewModel.propagateWeakly(to: self) | |
} | |
... | |
} |
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 | |
extension ObservableObject { | |
public func propagateWeakly<InputObservableObject>( | |
to inputObservableObject: InputObservableObject | |
) -> AnyCancellable where | |
InputObservableObject: ObservableObject, | |
InputObservableObject.ObjectWillChangePublisher == ObservableObjectPublisher | |
{ | |
objectWillChange.propagateWeakly(to: inputObservableObject) | |
} | |
} | |
extension Publisher where Failure == Never { | |
public func propagateWeakly<InputObservableObject>( | |
to inputObservableObject: InputObservableObject | |
) -> AnyCancellable where | |
InputObservableObject: ObservableObject, | |
InputObservableObject.ObjectWillChangePublisher == ObservableObjectPublisher | |
{ | |
sink { [weak inputObservableObject] _ in | |
inputObservableObject?.objectWillChange.send() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment