How to use ViewModel in an Android app?

Using ViewModel in an Android app allows you to manage UI-related data in a lifecycle-conscious way. ViewModels store and manage UI-related data that isn't destroyed on configuration changes, like screen rotations. This allows data to be preserved and also helps to separate concerns between the UI and data handling.

Step-by-Step Example of Implementing ViewModel

  1. Create your ViewModel class, which extends `ViewModel`.
  2. In your activity or fragment, get an instance of the ViewModel using `ViewModelProvider`.
  3. Observe the LiveData from the ViewModel to update the UI accordingly.

Example Code

class MyViewModel : ViewModel() {
    private val _data = MutableLiveData()
    val data: LiveData get() = _data

    fun updateData(newData: String) {
        _data.value = newData
    }
}

// In your Activity or Fragment
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

viewModel.data.observe(this, Observer { newData ->
    // Update your UI here
})
        

keywords: viewmodel android lifecycle ui-related data LiveData