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. The ViewModel 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:

  1. Create an instance of LiveData to hold a certain type of data. This is usually done within your ViewModel class.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    class NameViewModel : ViewModel() {

    // Create a LiveData with a String
    val currentName: MutableLiveData<String> by lazy {
    MutableLiveData<String>()
    }

    // Rest of the ViewModel...
    }
  2. Create an Observer object that defines the onChanged() method, which controls what happens when the LiveData object’s held data changes. You usually create an Observer 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
    23
    class 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)
    }
    }
  3. Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.

    1
    2
    3
    4
    mButton.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.