How to implement delegation pattern using MVVM and flow coordinators

Pavle Pesic
May 29, 2018 · 3 min read

When you start using MVVM and flow coordinators, some simple concepts like animated transitions or implementing delegation pattern don’t look so simple anymore. They still are, we need to adapt to the new architecture.

MVC + Delegation

We will look at a simple example. First view controller (VC) has date input filed. Second VC has a date picker, and when we select some date, it will have to notify First VC and update UI. This process should be very straightforward using the delegation pattern.

So what are steps in the implementation of the delegation pattern?

  1. We need to create a protocol (BViewControllerDelegate) and make weak delegate property.

Let’s try to use this idea with MVVM and flow coordinators.

Flow coordinator + MVVM + Delegation

We start by transforming BViewController because changes are minimal. Steps 1 and 2 are already completed, we have BViewControllerDelegate protocol, weak reference to delegate property and action done will call the method. We have implemented flow coordinator for transitions so, instead of using navigation controller for dismissing it, we will invoke onDismiss.

Now we are going to move the initialization of VCs to ViewControllerFactory class. Here we set BViewController’s delegate (step 4).

We use ViewControllerFactory because we don’t want to duplicate code (controllers with date picker are often reused, and we don’t want to write this code every time we need it). Now controller objects to have a much loosely coupled relationship with their dependencies.

FirstCoordinator class has an instance of ViewControllerFactory. The coordinator will instantiate view controllers using the instance and pass delegate reference.

As you can see the view model, not view controller, implements BViewControllerDelegate protocol (step 3). We extend AViewModel and it implements BViewControllerDelegate didSelectDate method. We are ready to go.

Results are the same as when we’ve used MVC pattern. Here is the code example.

Why should view model implement the protocol?

When we get the date or any other result, what do we usually do with that data? We need to present it and use it in some process.

  1. Because we are using the MVVM pattern view model has a responsibility to update a view, and we are doing it by setting dob property. We won’t talk about binding for now, but you can look an example for more details.

Conclusion

Using delegation pattern with flow coordinators and MVVM is very simple. Fundamental changes are that view model, not view controller, is implementing the selected protocol and we are setting delegate property in coordinator class.

Resources

  1. Project example

Thanks for reading :)

If this article was helpful and you want to hear more about similar topics, please clap, share, follow or comment.

Pavle Pesic

Written by

Senior iOS Developer & Mobile Team Lead