Sobes.tech
Middle

How to save the state of a ViewModel in Android architecture components?

sobes.tech AI

Answer from AI

To preserve the state of a ViewModel that survives process death, SavedStateHandle is used.

SavedStateHandle is a map-like storage associated with the saved state of an Activity or Fragment.

How it works:

  1. ViewModel receives SavedStateHandle as a constructor parameter.
  2. Data is saved in SavedStateHandle using the set() method.
  3. When the Activity/Fragment is restored, the saved data is automatically available in the SavedStateHandle of the ViewModel, which is recreated.

Example usage:

class MyViewModel(private val state: SavedStateHandle) : ViewModel() {

    private val _myValue = state.getLiveData<String>("myKey")
    val myValue: LiveData<String> get() = _myValue

    fun saveValue(newValue: String) {
        state.set("myKey", newValue)
    }
}

SavedStateHandle supports saving primitive types such as Int, String, Boolean, as well as parcelable and serializable objects.

It is important to understand that SavedStateHandle is intended for saving a small amount of UI-related data. For saving more complex or larger data, other mechanisms such as Room Database or DataStore should be used.