I have 2 independent ObservableObjects called ViewModel1 and ViewModel2.
ViewModel2 has an array of strings:
@Published var strings: [String] = [].
Whenever that array is modified i want ViewModel1 to be informed.
What's the recommended approach to achieve this?
Clearly, there are a number of potential solutions to this, like the aforementioned
NotificationCenterand singleton ideas.To me, this seems like a scenario where Combine would be rather useful:
To test this, first try pressing the "add item" button -- you'll see in the console that
ViewModel1receives the new values.Then, try the
Connect child publisherbutton -- now, the initial connection is cancelled and a new one is made to the child's iteration ofViewModel2.In order for this scenario to work, you always have to have a reference to
ViewModel1andViewModel2, or at the least, theconnectmethod, as I demonstrated inChildView. You could easily pass this via dependency injection or even through anEnvironmentObjectViewModel1could also be changed to instead of having 1 connection, having many by makingcancellableaSet<AnyCancellable>and adding a connection each time if you needed a one->many scenario.Using
AnyPublisherdecouples the idea of having a specific types for either side of the equation, so it would be just as easy to connectViewModel4toViewModel1, etc.