NikGreen
NikGreen

Reputation: 700

Passing data to an existing view model in MVVM-C pattern on iOS

I'm working on an application utilizing the Coordinator and MVVM patterns.

The coordinator protocol looks as follows:

protocol Coordinator: class {
    func start()
    func start(with deeplink: DeeplinkOption?)
}

The start method has the logic to start the current coordinator flow, e.g. create the corresponding initial view controller, view model, etc.

I've tried adding deeplink handling to the Coordinator protocol via the start(with deeplink: DeeplinkOption?) method. The issue is that I need to pass the deeplink data to an already existing view model in a specific coordinator and that coordinator doesn't hold the reference to the target view model. For example imagine the following stack:

The user is currently on the user details screen, and I need to pass the deeplink action to the chat screen view model. There's also no reason to re-create the chat screen from scratch as it's done in the start method since the chat screen is already in the navigation stack.

Is there a neat solution for this issue (and coordinator pattern overall) without storing the reference to a corresponding view model?

Upvotes: 2

Views: 1236

Answers (3)

psilocybin
psilocybin

Reputation: 1115

The Observer Pattern can be used to pass data between these components. An example (in a slightly different context) can be found here.

It involves registering observers with the data source and notifying these when the data source changes. In Swift you could do this using didSet { ... }, calling a method on the observers to inform them of a data change.

Upvotes: 1

Krupa Parsaniya
Krupa Parsaniya

Reputation: 287

You need to add observer for that.. No need to pass data in view model.

Calling observer from anywhere is the best pattern for MVVM to pass data

Upvotes: 2

Adnan Munir
Adnan Munir

Reputation: 139

Instead of passing data to the view model through Coordinator you can add an observer in the corresponding view model which you want to pass data. The observer will be listening for data and once you call observer from anywhere the data will be passed.

Overall through observer pattern this can be achieved.

Upvotes: 0

Related Questions