" Android Architecture Components with MVVM Design Pattern in the easiest way"
Aren’t you tired of hearing MVVM at every place, what it does, and it’s hype everywhere? I also got tired, so I decided to check out what it is and how is it different from existing Architectures that are out there and many are still using.
So MVVM is a new Architecture(or maybe not) but Google made it it’s advised Architecture indirectly for Android Application during Google I/O 2017 by introducing many Architectural Components (Now AndroidX Project).
So What actually is MVVM?
According to Wikipedia, MVVM facilitates a separation of development of the graphical user interface – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the data model). The view model of MVVM is a value converter, meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented.
If we talk about Android
It is exactly as Wikipedia says, MVVM is an architectural Pattern whose main motive is to keep View clean or separate of business logic. Keeping business logic and View separated makes Code Maintainability, Readability, and most important testability very easy.
Maintainability and Readability are easy as there is a separation of each layer so if we wanna make a change in business logic the view won’t get disturbed and vice-versa.
Testability, as the business logic is independent of views so it makes very easy to test the functionality without the presence of View itself.
and all that BLA BLA BLA !!!
Simply, MVVM is: Model-View-ViewModel
Model: It represents the data and business logic of the app.
Views: It’s the UI part of the application. (Activities, Fragments are some example of Views)
(The Model and View are same as they were in MVC or MVP whichever you know or prefer comparing it with)
ViewModel: It’s a separation layer(Don’t get confused and consider it as the Presentation layer, it isn’t Presentation layer), between view and model. The ViewModel interacts with Model and prepares data for View. Here is the difference in MVVM and MVP, in MVP whenever the data gets prepared it was feed explicitly to View so that it can get Updated but in MVVM view set observables on ViewModel so that whenever there is a change in data it automatically gets notified.
In MVVM, ViewModel is not aware of the view with which it is interacting or for which it is preparing data.
“Android new Architectural Components also include ViewModel that retains its state even after the change in configuration(like rotation) of the view it is linked with. So much of savedInstanceState overhead is relaxed but it is still useful.”
“In MVVM View observes ViewModel changes and ViewModel observes model changes.”
For observing the change in data or state earlier we use third-party libraries like RxJava, RxAndroid etc that were pretty good but with a limitation of not being aware of Lifecycle, due to which we had to handle or clear its disposable at the end of the lifecycle. Seeing this limitation Android took a step further and introduced LiveData with its other Architectural Components and yes it is Lifecycle aware.
LiveData is one of the components got introduced with other architectural components(I know you know this, don’t curse me if I am repeating this, there may be someone who for sure get benefitted). It is a type of object on which view can set observables so that whenever there is a change in the data wrapped in LiveData, LiveData will notify its observer. The benefit of LiveData is, it is Lifecycle aware(This is the awesome part). So if any view is observing on an object of LiveData is no more in memory then LiveData object won’t be notifying it at all as it knows that the observer is not available anymore.
ViewModel (Some points that I may have missed in above brief intro to ViewModel)
As discussed earlier it’s also one of the components got introduced with other architectural components(Please don’t curse). If we wanna prepare ViewModel we simply can extend ViewModel class(or AndroidViewModel), the difference between ViewModel and AndroidViewModel is that AndroidViewModel gets the Application object which again creates the dependency for Testing, so we try to minimize the use of AndroidViewModel until and unless there is a need for it.
I Know I have talked too much but give me few more moments I’ll wrap this up
Being serious: Few points that you should be aware of(it was my finding while searching for it on the web and found interesting)
ViewModel gets data from either Remote or local database, and we can use the concept of Repository(It is nothing but a Middleware that acts between Remote and Local database ) to implement SSOT(Single Source of Truth) that means ViewModel will always get data from only one source and that source will get updated timely totally dependent on our business logic.
For ex:- We can store some of our data in Cache/Local DB and while using the same data we can get it from cache itself or from the remote server for latest data, for this we will always request data from cache but in background will check for the updated value and update the cache accordingly so that we always will get the up to date data and that too from single source i.e cache in our case.
This was the main points about what MVVM is, and now I don’t think so anyone of you will get afraid of it.
Below is the source code that we developed while trying to implement MVVM, and will update it with new findings
Continue reading if you wanna dive deep in MVVM
The two most important factors that we have to take care:
1. Dynamic Request body
2. Centralized Error Handling
Dynamic Request body
If we just use above mentioned components we can achieve and use MVVM Architecture but with the limitation of static request body that may be required to be passed to API while requesting data from Server
For the above-mentioned problem that’s serious too, Android has created a class ViewModelProvider that can be used to Create a ViewModelProvider instance and can be used to inject the required data to our ViewModel so that it can get the needed response.
Centralized Error Handling
As we are using LiveData in our example so there isn’t any scope of error handling as the LiveData notifies for the data changes and there is no way in LiveData to notify for Error that may occur for any reason be it server side or client side.
To resolve this issue I came across “egbai smile mmumene’s blog on proandroiddev” that suggested overriding existing functionalities of Retrofit response callback and creating a DataWrapper for other Error and Exception, so that if we update the value of Error or Exception then it’s observer will get notified of it and can perform respective action.
“You can find the implementation of this in example available on our provide Github repository link. https://github.com/Startxlabs/MVVM_Android”