Use of ViewModel with LiveData in Android
In Android Architecture Components, ViewModel and LiveData are used to change values and notify observables with respect to android lifecycle.
The
ViewModelclass is designed to store and manage UI-related data in a lifecycle conscious way. TheViewModelclass allows data to survive configuration changes such as screen rotations.
LiveDatais an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
How to use ViewModel with LiveData
Follow these steps to work with ViewModel and LiveData objects:
Create an instance of
LiveDatato hold a certain type of data. This is usually done within yourViewModelclass.1
2
3
4
5
6
7
8
9class NameViewModel : ViewModel() {
// Create a LiveData with a String
val currentName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
// Rest of the ViewModel...
}Create an
Observerobject that defines theonChanged()method, which controls what happens when theLiveDataobject’s held data changes. You usually create anObserverobject in a UI controller, such as an activity or fragment.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class NameActivity : AppCompatActivity() {
private lateinit var mModel: NameViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Other code to setup the activity...
// Get the ViewModel.
mModel = ViewModelProviders.of(this).get(NameViewModel::class.java)
// Create the observer which updates the UI.
val nameObserver = Observer<String> { newName ->
// Update the UI, in this case, a TextView.
mNameTextView.text = newName
}
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.currentName.observe(this, nameObserver)
}
}Attach the
Observerobject to theLiveDataobject using theobserve()method. Theobserve()method takes aLifecycleOwnerobject. This subscribes theObserverobject to theLiveDataobject so that it is notified of changes. You usually attach theObserverobject in a UI controller, such as an activity or fragment.1
2
3
4mButton.setOnClickListener {
val anotherName = "John Doe"
mModel.currentName.setValue(anotherName)
}
This is a simple example that shows you how to use ViewModel and LiveData in Android. You can find more details in this.