Android App Architecture ViewModel Concept

Mohit Sharma
2 min readMay 22, 2017

--

In Google IO 2017, Google recommended the App Architecture that can be used to make app more stable and robust. The application architecture can be divided into different parts, explained below.

(1) Activity/ Fragment or Views: This component will show UI of the app that user sees and also pass any event happened on the UI to ViewModel which will react for those events. One thing to remember is, Our UI component should never directly talk to Repository. They should always pass event or get the data from view model which will be shown in the UI.

(2) ViewModel: This component should have all the business logic and also provide data back to the View. One important thing about the view model is, it will survive the config changes too. So in case of config change happen, the activity will be recreated but view model that is created first time will be used which is explained in below diagram, taken from the Android documentation.

NOTE* Another thing to make sure we should never pass context to view model.

ViewModel Lifecycle

(3) Repository: This module handles data operations. This module will decide from where we should get data from network or local db. It abstract the data source.

App Architecture

One important thing to remember is each component should talk to component which is above or below only. Our view should never talk to Repository. Same way View Model should never talk to Web service or Data base.

You can find sample code in this article in which i have implemented the above pattern.

For More Info: https://developer.android.com/topic/libraries/architecture/guide.html

--

--