How to use ViewModel in Android

Android provides multiple methods to execute long running code off the UI thread while posting the results of the code to the main UI thread. CursorLoader is one of such method which is based on Android’s Loader framework. CursorLoader is a AsyncTaskLoader which is used to perform cursor query on a background thread. Cursor Loader loads data in a background thread and presents the results in the main UI thread. The second most important aspect of loader is that they monitors the data source for any update and re queries if there is any change detected. Thus the UI is always up-to-date with any new data changes.

In SDK 28.0 Android framework deprecated the use of Loaders. Thereafter the recommended option is to use Androidx ViewModels and LiveData. ViewModel is a class which prepares and manages  the data for Activity or Fragment. LiveData is a data holder class that is observed by VideoModel for any modifications in the data. Let’s see the use of ViewModel and LiveData by an example.

In one of the earlier post I showed how to get list of applications installed in Android device. I will show now how to use ViewModel and LiveData to present the data in a RecyclerView.

The xml layout of the activity is defined in main_activity.xml

Activity code is defined in MainActivity.java

Fragment class is defined in MainFragment.java

Time to check the view model class. In this example we will be using AndroidViewModel which is a custom class extended from ViewModel. AndroidViewModel provides Application context that can be used to as a context. In this example we are using AndroidViewModel to get package manager instance. The application context is available in the constructor method provided by AndroidViewModel.

Create MutableLiveData which exposes set and post methods to post the data to the observable. postValue is used when the data is posted from background thread. setValue is used when the data needs to be set from main thread.

Fragment and Adapter XML layouts are defined below.

main_fragment.xml

apps_list.xml

Download source code from the link here.

ViewModel
ViewModel
ViewModel.zip
Version: 1
440.3 KiB
34 Downloads
Details

Leave a Reply