MVVM Architecture in Android
August 18 2019 0 Comment

Android have a much more complex structure as compare to desktop. Because android app contains multiple component such as activities, fragments, services, content providers, and broadcast receivers. Each component have different life cycle. 

 

MVVM  Architectural principles has  two basic principles :

  • Separation – Separation of concerns principles says UI-based classes (Activity, Fragment) should only contain logic that handles UI and operating system interactions. By keeping these classes as lean as possible, you can avoid many lifecycle-related problems. 
  • Drive UI from a model – Second principles is you should drive your UI from a model, most preferably a persistent model. Models are components that are responsible for handling the data for an app. 

This architecture pattern empower you to write a clean and maintainable and testable code. The MVVM decide three main categories of component, which helps the concept of separation of concerns Model, View and ViewModel. 

Model 

Repository component which acts as a single source of truth all the data can also be considered as a part of the Mode. it can be more than one repository in a large application. Model where are we include all the business logic. 

If you are storing data locally you would have room database classes. In case of getting data from remote server using REST API you may have Retrofit instance and Retrofit interfaces also. 

Repository acts as a single source of truth for ViewModel. In other words, ViewModel gets data from repository. ViewModel does not concern how repository gets those data. Repository isolated data layer that provided centralized and consistent data. This repository pattern makes it easy to add new data source also this allows us to write unit test for business logic separately. 

 

ViewModel 

ViewModel is like a middle person between View and Model. It provides data for the View by getting from the repository. Let’s focus on diagram, you can see the arrow only pointing in one direction, towards to ViewModel. This means the ViewModel never knows about the View using it. We can make this possible by setting the data observable using LiveDataSo we don’t have to directly update the View from ViewModel any data change happen. 

In MVVM we can directly interact with views mainly Activity, Fragment, Supporting Adapter. It should handle only the immediate interaction with the uses you should never include any business logic like communicating with database or Rest API inside the Activity and Fragment or Adapter. in MVVM View observes the data from ViewModel and ViewModel observes data from Repository. Repository get data from local and remote server. 

 

If you would like to know more about material design refer to this  article.  

At Emqube we focus on building high quality hybrid mobile apps. Contact us if you would like us to build an app for you.