Communicate between View Controllers with RxSwift

If you are still not sure on how to get started with RxSwift then this article is for you.

I have read many articles about RxSwift but from understanding the theory to utilizing that knowledge practically was a deep curve.

In this article we will create a very simple iOS application that will use RxSwift. We will use the concepts of RxSwift and apply them in this application. I will be skipping the basics of RxSwift as there are many beautiful articles which explains them. For reference you can have a look here. Its a lovely article by Sebastian Boldt 👨🏻‍💻.

We will be taking a very basic scenario in this application i.e.making view controller communicate using RxSwift.

Lets get started…

Basic Setup

Create a new project in Xcode and initialize pod for the project and add the following in your pod file.

pod file

Replace YOUR_TARGET_NAME and then, in the Podfile directory, type:

$ pod install

Fast forwarding….

Add a new View controller(I named it NewViewController) so that your main storyboard looks like this:

Our two View Controllers

When you tap on change background button it will open the new view controller and when you tap on any button on the NewViewController it will change the color of the MainViewController.

Communication via established cocoa pattern

Cocoa delegate pattern

If you were building this using established cocoa pattern, then your next step would be to add a delegate pattern so that our NewViewController could talk back to or MainViewController.

Communication via Observables

Open up your NewViewController, add the following variable to your view controller class:

Here we have created a Subject named selectedColorSubject. This will emit the selected colors and an Observable named selectedColor that exposes the subject observable.

To know about Subject and Observable, refer the link mentioned above.

We will add a function named changeColor, it will be responsible for emmiting a new color value when any of our buttons are pressed and once we emmit the value we should navigate back to our previous screen.

Our function looks like this:

changeColor function

selectedColorSubject.onNext(color) emmits the new color value and after that we navigate back.

Lets make sure our buttons action event call this function

By now our view controller looks like this:

NewViewController

Now lets go to our mainViewController

Add the following code in your button action event

When we tap on changeColorButton we navigate to our NewViewController. As we saw that selectedColor variable in NewViewController returns a type Observable hence we can subscribe to that sequence.

This way whatever value is emmited by that observable can be captured on here on our MainViewController. You can think it as a simple KVO.

Hurray!! We have finished our first RxSwift powered application.

Source code on Github.