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
ViewModel
class is designed to store and manage UI-related data in a lifecycle conscious way. TheViewModel
class allows data to survive configuration changes such as screen rotations.
LiveData
is 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
LiveData
to hold a certain type of data. This is usually done within yourViewModel
class.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
Observer
object that defines theonChanged()
method, which controls what happens when theLiveData
object’s held data changes. You usually create anObserver
object 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
Observer
object to theLiveData
object using theobserve()
method. Theobserve()
method takes aLifecycleOwner
object. This subscribes theObserver
object to theLiveData
object so that it is notified of changes. You usually attach theObserver
object 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.