Creating Your First RxSwift App

Smriti Arora
The Startup
Published in
10 min readJan 7, 2021

--

Before we dive into using RxSwift for our app. We should definitely ponder over the “why factor” for the same. Why do we need RxSwift and why not use the conventional method.

So, the major drawback with the conventional method is that we have to manually maintain states and operate the calling of update state functions leading to huge if-else ladders, switch cases, etc. To cut all this chaos, an angel 🧚🏻(RxSwift) descends from the heavens and takes us to the land of Reactive programming. (Sorry about that! The hidden poetess in me tends to peep out sometimes!🤣)

Image source: https://thumbs.gfycat.com/GrandAngryBackswimmer-small.gif

While there is a lot of buzz of Reactive programming in every technology be it javascript, spring, python, and many others, iOS doesn’t lag in having a very own reactive version of itself - RxSwift. So why not program your iOS apps in the famous as well as an effective way, the REACTIVE way!! But before we could dive into the “technicalities” of how to create your first very own RxSwift app, you may be curious about why do we need to code in a new way when the old one is working well? But trust me RxSwift can work wonders if understood and used well. This project requires some basic understanding about RxSwift know-hows, so if you want to take a look at it you can jump on to this link here to look at the basics of reactive programming with swift.

Image Source: https://avatars0.githubusercontent.com/u/15903991?s=280&v=4

Since it is our very first attempt at using RxSwift, so the project that we are going to make it really simple, but it will still give you a good kick start towards reactive swift programming. Also, this project uses MVVM architecture, if you are not familiar with it you can jump into this link right here MVVM architecture for iOS.

This project is a simple iPhone app which displays a list of users obtained from a public API. It lets you search a user from the list and also see if the user is one of the favorites or not. The app also shows the details of the user when you click on the user. You can also ‘star’ and ‘unstar’ a user, as in, favorite or unfavorite a user on the details screen.

So this is what you will be able to achieve in your project by the end of this article.

  • Obtaining JSON data from API.
  • Display a list of users in a table view.
  • Perform a search on the list of users.
  • Select a user to view its details.
  • Lastly, the ability to favourite a user on the details screen.

For a better understanding, here is a flowchart that explains what’s going on in here: 👇🏻👇🏻

Application flowchart

Without further ado, Let’s get started!

Setup a new Xcodeproject

First things first! Let’s start by including the RxSwift library in our project. Here I have used cocoa pods to do so. If you want to learn how to include third-party libraries using cocoa pods from scratch you can go to this link here: Including third-party libraries in your Swift project using Cocoapods.

So insert these lines in your podfile under the name of your project target as shown here and run the pod install command:

A screenshot of podfile of including RxSwift pods

This will include the latest available version of RxSwift and RxCocoa library in your project. Wait a minute…! Now you may think that what is RxCocoa? 🤔Why do we have to include that? So, RxCocoa basically contains UI specific functions built on top of the RxSwift library. These functions help us to configure and use the swift UI components in a reactive way.

With this done, we are all set to use RxSwift in our project.

Creating Views

Create two view controllers embedded in a navigation view controller. Then, simply drag-on the UI elements. So that the board looks like this:

So in the end, you should have a:

  • MainViewController: which has a search label, a search text field for search input, a table view with table cell having User’s Name as well as its favourite status.
  • UserDetailViewController: this shows user details, this is the place where we can alter the user’s favourite status by clicking on the star button.
  • UserCell: A cell class to configure the table cell.

After adding the components on the storyboard, create corresponding classes and attach the UI component outlets.

That’s all about the UI here. Our skeleton is ready. Now getting into serious business i.e. using RxSwift to give life to this skeleton project.

Creating the Model class

We’ll start on by creating a codable class for our JSON object that we will be receiving from our API request. I’ve created a struct DataModel.swift of Codable type to map the received data. Here comes the First M of the MVVM architecture which stands for Model, a model is a structure which holds the raw data which is received by the API/data source. It is of the codable type which holds the decoded data from received JSON.

Next, we create a class for calling the API. Create a file named APIRequest.swift. In this class, we create a function named callApi() which returns an observable of type codable(That we created earlier) to map the received data. In the call API function,

  • We create an Observable of type T by using the create function which returns a Disposable.
  • Inside the observer, we call the API by using the URL session object created on the top of the class (refer. image).
  • Once we receive the response, we try to decode it, if the decoding is successful, the observable emits the onNext event with the decoded data.
  • If the decoding ends up being erroneous, observer emits onError event with error as value.
  • Lastly, since the observable.create function requires a Disposable object in return, we return an object of Disposable type with the help of create function and inside it, we cancel the session data task.

Now, We have the user data from API. But apart from the user data received we need to associate a bool property which indicates if the user is favourite or not. So we create a new structure called UserDetailModel, which contains user data along with a favourite property with initial value as false of type behavior relay so that whenever we change the favourite status it automatically updates the star image indication. Along with the favourite property we have also created an observable of type bool which takes the favourite status as observable so that we can subscribe to the favourite property of the model. This is how the structure looks like :

With this, we have a final data model as well as the API calling class ready.

Next steps are calling the API class to obtain the data from API and displaying it on the screen.

Creating the View Model Class

Since we are following the MVVM architecture, the next step is to create a view model, A View model does all the operational work on the data and makes it eligible for being displayed on the screens. Once done, the view model passes the data ready for display to the views.

In the view-model class,

  • We create an instance of the API Request class.
  • An observable of type user detail array.
  • A Behavior relay userViewModel of type UserDetailModel array.
  • An observer of userViewModel, so that we can subscribe to it.
  • Lastly, we create a dispose bag.

A Dispose bag is used for memory management, it keeps on collecting subscriptions and then finally it disposes them off when the controller memory is deallocated. It ensures that there are no memory leaks.

Next, we create the function fetchUserList(), which will be used to call the API and obtain data from the API. Once we get data from API we assign it to the users observable that we created earlier in the class.

Next up, since we want data in the form of UserViewModel data structure, we bind the value obtained from API to a closure that maps the [UserDetail] observable type data to [UserDetailModel]. Finally, we pass the formed UserDetailModel array to userViewModel behavior relay.

This is how the view-model looks all done.

Now, we have data mapping function ready in our view model. The only task left is to display it on screen.

Feeding data to the views

The last step, towards completing the MVVM structure of our app is creating Views. Views are responsible for displaying the data to the user and take inputs from it. Views display the data from view models to the user.

So once we have our data operated in view models and we are ready to display them to our user. Let’s get back to the view controllers that we created earlier.

In the MainViewController:

We will create an instance of ViewModel class, userViewModelInstance, two empty behavior subjects, userList and filteredList to save the data received from the view model. Now, why two? We’ll get back to that soon.

Now, we call the fetchUserList() function which will call the API to fetch the user data. We call this function in the viewDidLoad() of the controller, this fetches the data and saves it to the behavior relay subject of the view model.

Let’s bind the received data to our view components, using a function called bindUI(), this contains all of the binding view-to-data stuff. So our bindUI() function is called in viewDidLoad after the API call and it contains the following operations:

  • We first subscribe to the view model’s observer to receive the API data from it and save its value in userList and filteredList by using the accept function.
  • Next, we bind the filteredList to tableview to provide a data source for the tableview. Here, CellIdentifier is the reuse identifier of the table cell and UserCell is the cell class that was setup earlier in the project to configure the cell. Finally, we pass the data model to configure cell function of cell class.
  • Configuring the row click: To set up the cell click action we use .itemSelected function(from RxCocoa) and perform the task inside its onNext closure. So here I’ve shown the complete user detail’s in the UserDetailViewController on click of a cell.
  • We pass the selected user’s detail to the behavior relay object of UserDetailViewController.
  • Next on, we subscribe to the isFavoriteObservable of the UserDetail model so that the main view automatically refreshes on an update of the favorite status from UserDetailViewController.
  • and finally, we push the view controller in the navigation stack.

Here I have already created a global instance of UserDetailViewController in the main view controller. You can also create it inside the onNext closure.

  • Setting up the search field: To setup the search text field we use the combine latest method of observable to subscribe to the changes in the text field. Now, here we use the second data model usersList that was discussed earlier.
  • Basically what we do is, we take the complete list of user’s from the userList, filter the names as per the search string and bind the obtained results to filteredList, the model which actually configures the cell data. Complicated stuff? 😥 Not really, please have a look here…
  • filterUserList is the function which does the filtering work.

Congratulations! You guys made it till here!

We just have one last function left for this application to be fully functional using RxSwift i.e. the favoriting of the user from detail screen. Let’s jump in.

  • Here we have some UI components attached to the controller. But we don’t have any action for the favorite button so we add the functionality on the tap of a button using rx.
  • So, basically on click of the button, we want to toggle the button from selected to unselected and vice versa. So we bind the tap of a button to a closure that obtains the current state of favorite and button and updates it with its opposite value.
  • Next, we feed the labels with data from the model to display on the screen. For this, we subscribe to the user detail observer so that we get the data value from its subject.
  • Along with setting up label values and title of the controller, we also set up the favorite button image as per the favorite value and also subscribe to its observable so that whenever it’s value changes the favorite button image gets updated automatically.
  • setupFavoriteButtonImage is the function that sets up the favorite button image as per the status of the user value’s favorite subject.

So that’s pretty much it.

Voila! you have your very own working application developed in RxSwift.

Hope this article helped you with your initial steps into RxSwift. You can find the complete project on this GitHub link here: UsersListwithRxSwift

Also, these are the links mentioned in the article above:

Feel free to give your valuable inputs in the comments sections, and if there is any other way I could have done it better, please let me know here so that we can all grow together as a community… 👬👫👭

Also, if the article was useful, please show some love by giving claps… 😍

--

--

Smriti Arora
The Startup

iOS developer, content creator, music enthusiast ✨✨💫💫