MVVM with RxSwift : User Login

Yuvraj Pandey
Swift2Go
Published in
5 min readAug 17, 2018

Are you bored of following the same old MVC architecture pattern for developing your iOS app’s and are open enough to try a new pattern then hey! you are at the right place.

Note : If you are unaware of what RxSwift is then i would recommend you to read through my previous article that would walk you through some very basics of RxSwift so that you feel comfortable with the code that i would be explaining in this article.

Now i assume that you would have some basic understanding of what RxSwift is capable of and how to tackle with it. So now moving ahead lets talk about MVVM (Model — View — ViewModel) Architecture before we deep dive in to some coding stuff.

MVVM is very similar to MVC. It depicts the tightly coupled nature of the view and controller and introduces a new component.

Under MVVM, the View and the ViewController both are very closely connected to each other and we treat them as one. Views still don’t have any references to the model directly & neither do controllers. Instead, they reference the new component ViewModel.

The ViewModel is an excellent place to put all your validation logic for user input, presentation logic for the view, initiation of any network requests, and other miscellaneous code. The one thing that does not belong in the ViewModel is any direct reference to the view itself. The logic in the ViewModel should be just as applicable on iOS as it is on OS X. (In other words, don’t #import UIKit.h in your view models and you’ll be fine.)

Since presentation logic — like mapping a model value to a formatted string — belongs to the ViewModel so that ViewControllers themselves become far, far less bloated & small in number of line of code’s. The best part is that when you’re starting off using MVVM, you can place only a little bit of code logic in your ViewModel, and migrate more of it over to them as & when you become more comfortable with the paradigm.

iOS apps written using MVVM are highly testable; since the view model contains all the presentation logic and doesn’t reference the view, it can be fully tested programmatically. Enough of theory now its time to get our hands dirty with some code samples which will give you to get a glimpse of how MVVM can be implemented efficiently.

1) LoginModel

  • LoginModel is a class that stores login credentials i.e username & password.

2) ViewModel

ValidationViewModel :

  • Here we define a protocol ValidationViewModel which consists of some basic definition & rules that we will be using to test our case the Username (Email Id) & Password.
  • The variable errorMessage will hold a pre-defined error message to display to user or a message received via API response.
  • Variables value & errorValue will be our observables that we will bind to our views later on.
  • Also we declare a function validateCredentials() which performs the validation as required in respective ViewModel.

PasswordViewModel :

  • Our ViewModel conforms to the protocol ValidationViewModel which then adds the properties defined in it.
  • We initialise the acquired properties with some default values.
  • We then provide implementation to our function validateCredentials() in which we validate the password length to be between 6 to 15 characters & according we initialise the errorValue variable.

EmailIdViewModel :

  • Here the implementation is similar to what we had discussed for PasswordViewModel except the part of validation where for Email Id field we check the validity of the Email Id entered by the user.

LoginViewModel :

  • This is the main ViewModel that actually handles all the user interaction on the view of Login.
  • Here we create instances of our password & email view models & also define the observables i.e Variable as isSuccess, isLoading, errorMsg which we will bind to the view for reactive data changes.
  • In validateCrentials() function we actually compare the field values by calling the respective ViewModel’s function.
  • Finally the loginUser() initialises the model with values , then we create a request for the api comprising of email , password & at last we initiate a API request. On either success or failure response we update the observable’s that we have defines earlier in our case isLoading, isSuccess, errorMessage which instantly reflects in the view using binding thereby making it reactive.

Note : When you subscribe for an Observable the Disposable keeps a reference to the Observableand the Observable keeps a strong reference to the Disposable (Rx creates some kind of a retain cycle here). Thanks to that if user navigates back in navigation stack the Observablewon’t be deallocated unless you want it to be deallocated. To break the retain cycle somebody needs to call dispose on the Observable. If Observable ends by itself (by sending completed or error) it will automatically break the retain cycle. In any other scenario, the responsibility to call the dispose function is in our hands.

3) ViewController

  • Now finally we come down to our view i.e ViewController where data gets reflected by ViewModel in a reactive manner.
  • In createViewModelBinding function we bind the email & password fields with their respective ViewModel’s data variable which in short keeps the textfield text & data variable value in sync. So as an when the value of email textfield changes , the data variable value also changes.
  • The login button tap listener at first closes the keyboard by self.emailTextField.resignFirstResponder(), then validates the credentials and accordingly calls the loginUser function for processing.
  • In createCallbacks function we subscribe to the isSuccess & errorMsg observable, so that if any time its value changes we get a call back in our View and according the process can be executed.

That’s it for this article hope you would have learn something useful from it. So If you have any thoughts or suggestions, feel free to leave a comment below. Don’t forget to share your love by clapping for this article as many times you feel like.

You can follow me on Twitter , Github , LinkedIn , Facebook.

Happy Coding 👨‍💻 🎊.

--

--

Yuvraj Pandey
Swift2Go

Working towards striking an impact using technology for making this world a better place to live in ✅