An easy example on how to use Jetpack ViewModel and LiveData
Jetpack broken up into four main areas: Architecture, Foundation, Behaviour and UI.
ViewModel
ViewModel helped to achieve two things:
- help the project to adopt MVVM architecture
- hold the data in the memory in a life-cycle manner
One of the benefits of using ViewModel
is the data can be kept while screen is rotated.
LiveData
LiveData can apply observer pattern
to a variable, thus you can bind the data changes to the UI component.
One example of using both ViewModel
and LiveData
We are going to create a simple example which only has three parts on the UI:
Simply as it is, +1 button will add the total value by 1, -1 button will minus the total by -1.
Step 1: install ViewModel and LiveData plugins.
On the Google Android’s document website, you can install ViewModel along with lifecycle or you can just install the target plugin.
I would recommend to install the following two plugins if you are only use ViewModel and LiveData:
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
Step 2: MyViewModel.kt
Create the ViewModel inherited from ViewModel
class with only one observable variable inside: num, which is used to hold the total shown in the screenshot.
Step 3: MainActivity.kt
Here is the complete code for MainActivity:
Step 4: Layout of the MainActivity
By far you have successfully implemented the viewModel and liveData in your project.
- If you are running the app now, you can see +1 button will increase the total value, -1 button will reduce value.
- If the screen is rotated, the total value will kept on the screen.
The complete project you can download from: https://github.com/arkilis/jetpack-mvvm
Reference
Originally published at https://needone.app on July 22, 2020.