How to use RxSwift with MVVM pattern part 2

This is the second post on how to use RxSwift with MVVM series. In the first part we set up RxSwift from Cocoa pods and checked how to use BehaviorRelay, Observable and PublishSubject. This time we will create a view that we can use to create and update friends to the server. We will also see how to validate the inputs in all of the textfields before activating the submit button. After, that we will check how to bind data back and forth in UITextField, between the view model and the view. 

 
In case you are not familiar with the friends app, it is an app that you can use to download a list of friends and display them in a table view. You can also add, remove and update friends. I’ve implemented the application using MVVM architecture, and of course, I wrote the backend with swift using Vapor! If you want to learn basic MVVM without RxSwift, check out my old post MVVM pattern with Swift application
You can get the source codes for the application from GitHub, just remember to check out the RxSwift branch. You can, of course, follow this post also without the source code.  But now, let’s get down to business!

Creating and updating a friend using RxSwift

So, our goal is to add friend information to the server, and also to update that information. We’ll do that using the same view.

Add and edit friend RxSwift

Add and edit friend RxSwift

We have a view that you can use to enter the first name, last name and the phone number of a friend. First, we define a protocol named FriendViewModel. Then, we will have two view models that conforms to that protocol: AddFriendViewModel & UpdateFriendViewModel. In this tutorial we’ll dive into UpdateFriendViewModel. It does all the same things as AddFriendViewModel and fills the text fields with friends information when we open the view to edit friends information.

As in the first part with deleting a friend, also cell tapping is set up with a function from the rx extension. Now we use modelSelected function and subscribe to events that it emits. First, we’ll check that the cell type is normal and bind the viewModel with if case let syntax. Then, we’ll store the view model to a new ReadOnce object and perform the wanted segue.

ReadOnce to the rescue

ReadOnce is a helper class that makes sure that we are not using an old view model when opening the view:

The value is stored in a private var value. You can only access it using the read function. In case you have read it once, isRead is set to false. The next time you’ll call this it will return a nil value instead. We always create new ReadOnce object when we are proceeding to the new view, and this makes it a lot safer. Now there is a very small change, that an old value is messing up the new view creation.
 
Then we can check if we should perform the segue. Inside the shouldPerformSegue, we can check the isRead value. If it returns false, then we can proceed.

Now that we know segue is performed, we will set the view model in the in prepareForSegue like this:

This way we’ll make sure the view controller is always opened with correct information.
One interesting thing here is the updateFriends observer. When we are returning back to the friend list after we have updated a friend, we want to make sure our list is up to date. That is why we set up an observer to get an event when we have to update friends from the server. We also want to make sure that this observer is released from the memory. It might be a problem if we have an active observable subscription to a view controller that is released from the memory. We can be sure that we have canceled the subscription when the “ONCOMPLETED” is printed in the console. We’ll come back to this issue in the FriendViewController code. I’ll show you then how we can prevent the memory issues.
 
Now we know how to open the view to edit a friend. Next, let’s take a look how to implement UpdateFriendViewModel!

RxSwift type definitions in FriendViewModel protocol

Take a look at the protocol defined below.

All the variable definitions are familiar to us by now, but let’s have a quick recap. We have BehaviorRelay, Observable and PublishSubject. As we remember they are all observables. Observable sends OnNextOnError or OnCompleted to change the state. With BehaviorRelay we use the accept() function to update it’s value, which is then emitted to the subscriber with onNext event. PublishSubject acts the same as Observable but it can also subscribe to other observables.
 
I know this was a quick review of the RxSwift observables. In case you want to recap how to subscribe to events etc, please check the first post of the series.  Now, let’s move on to the UpdateFriendViewModel to see how we should use all those.

UpdateFriendViewModel implemented with RxSwift

As said, UpdateFriendViewModel conforms to FriendViewModel. Let’s check the implementation of the variables first:

At the top, we have PublishSubjects. They emit events to show error, navigate back to friend list view and when the user taps the submit button, sends information to the server. Below those, we have the good old disposeBag. Then we have all the friends information defined as BehaviorRelay. We also have the title for the view: “Update Friend”. The last two public variables are onShowLoadingHud and submitButtonEnabled.
 
We want the loadInProgress to be private variable. This way we can’t change the state in the view controllers side. Instead, we have defined onShowLoadingHud as a computed property. This is a public observable we can use in the view controller side. It returns the loadInProgress as an Observable. We subscribe to this observable in the view controller side and get notified when it changes its statedistinctUntilChanged makes sure the value is only sent if the new value is different from the previous.
 
SubmitButtonEnabled is a bit more interesting. It combines few variables and validates the inputs. Then it decides if the button should be enabled or not.

Validating input with RxSwift

To do this we have to introduce a few more private variables:

We have a computed variable for every input the user can edit. All the variables return the original variable as an observable. For example: we tie firstnameValid with firstname. After the asObservable we use map and check if the value in the variable is longer than zero characters and return a boolean.
 
Now, let’s look at the submitButtonEnabled observable again. We can see that it is observing all those private variables we defined. It takes the latest values emitted and combines the boolean values. If all are true, then the button is enabled and the user can update information to the backend.
 
The last two variables in the view model have are:

AppServerClient is the layer for all networking in the app. When user updates friend information to backend we use appServerClient. We need the last variable friendId to identify the friend which user is updating.

UpdateFriendViewModel constructor and submitFriend function

We are almost done with the view model. Next, we will check the constructor and friend information sending. Let’s start with the constructor:

Inside the constructor, we first set all the friend information that we get from the FriendCellViewModel. Then we’ll set appServerClient. We want to use dependency injection here to make the class testable. And last we will set up the submitButton. We subscribe to the onNext event and call submitFriend when user clicks the button.

Submit friend information to the server

Submitting friend information is done like this:

First, we’ll set loadInProgress true, to active the loading indicator. Next, we’ll call patchFriend function from the AppServerClient. It takes friend information as parameter and returns an Observable we can subscribe to. When the request is a success, observable emits onNext event. Then we’ll hide the loading indicator and emit onNavigateBack event. This way we’ll return to the friend list view.
 
If something went wrong observable emits onError event. We’ll hide the loading indicator, and create SingleButtonAlert with the correct title, message, and action. Since the alert is dismissed automatically after the button press, the action here is only to print text in the console to see that the button press works. After that we’ll emit onNext event for the onShowError to present the alert. One thing you might be wondering here is the getErrorMessage function. At the bottom of the UpdateFriendViewModel we have defined a private extension for PatchFriendFailureReason. We use it to convert known error messages to a human-readable message presented to the user:

It checks if PatchFriendFailureReason enum contains a known value and returns a text we can present in the error popup.
 
Now we’ll move on to the view controller side!

RxSwift with MVVM FriendViewController

We use FriendViewController to create a new friend and also to update an old one. At the top of the file, we have familiar definitions for UI components and view model etc.

Here we also see the updateFriends variable which we already talked about. With this, we’ll inform the friend list to update itself. As we discussed, this can lead to memory issues. We want to make sure that we release the observer from the memory when the view controller is released. We can make sure this happens by calling onCompleted for the observer in the viewWillDisapper:

Binding view model values

Now, let’s check how we handle the binding between the view model and the controller:

When view is loaded we’ll call the bindViewModel function. Inside we’ll make sure we subscribe to all events that change the UI state. Furthermore, we also make sure that we update all values to view model that the user can change in the UI. First, we’ll unwrap the viewModel to get rid of all the optional handling. Down the road, this makes the code a lot cleaner. Next, we’ll set the title for the view. title = viewModel.title.value. Then we have a bit more interesting things to do.

Binding UITextField to BehaviorRelay and back again

The text fields and the friend values in the view model need to be bound both ways. When the view controller is opened, we want to fill the text fields in the form with the values from the view model. Also, when the user changes those values we want to update the new values to view model. To do this we make a private function: bind(textField: UITextField, to variable: Variable<String>)

BehaviorRelay is the variable we have on the view model side. We’ll bind that value to textfield using the text property from rx extension. This way we always update the textfield when we open the view for the first time.
 
With textField we’ll also use the text variable fromrx extension. Then we’ll use unwrap functions since the text variable is an optional (to make sure it actually contains a value). And finally bind it to the view models variable. We also add both of the parameters to disposeBag, to make sure won’t have any memory issues.
 
This is a lot cleaner solution. It saves us a lot of lines compared to calling those to all text fields and view model variables separately. I really like it, I hope you do too!

Continuing with the bindViewModel

Next, let’s activate and bind submit button and present loading hud and errors to the user.

Again we are using the rx extension. We bind view models submitButtonEnabled to the buttonSubmit and also set tap handler to view models submitButtonTapped.
Next, we’ll subscribe to onShowLoadingHud. Again we use map to get the boolean value from the event that it emits. And call for the setLoadingHud to present or hide the loading hud.

onNavigateBack is pretty straight forward. Only thing we need to remember here is to emit the updateFriends event to update friend list. With onShowError we once again use map to get the boolean value. Then we call the presentSingleButtonDialog to display the error.
The rest of the code is just handling the text fields activation. Incase you want to know how it is done, please refer to the MVVM with Swift application part 3 and search for activeTextField.

Conclusion

And that is all that I wanted to go through with you today! As said I won’t go through the AddFriendViewModel in this post. It is so similar to UpdateFriendViewModel that you can do it by yourself.

 

With this one and previous post, we have now gone through the basics of RxSwift. We know how to work with UITableView. How to handle subscriptions to observables back and forth view model and view controller. We also went through the basic validation of user input data and more! However, we still have some work to do! Next time we’ll check how to unit test the application we have created and we also haven’t gone through the network layer.

 

I hope you have liked the series so far! Incase you have any questions or comments, please post a comment or message me on twitter! If you liked the post please spread the word and tell your friends about it. So until next time, have a great day my friend!

This article has 2 comments

  1. Pranalee

    Thank you so much for the tutorial. it helped me a lot to understand the concepts of MVVM and Rxswift

    • Jimmy

      Thanks Pranalee,

      Makes my day to hear that I could help! 🙂