Saving instance states inside ViewModels
ViewModel components have the capability of saving the instance state, like how Activity and Fragment components can save their state through onSaveInstanceState, or how in Compose, we can use rememberSaveable. This can be done through the SavedStateHandle class and used in a ViewModel constructor, like in the following example:
class MyViewModel(
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
}
To store and retrieve data, we are presented with the get and set functions, each requiring a key for the data we wish to save:
private const val MY_KEY = "my_key"
class MyViewModel(
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
var myValue: String = ""
set(value) {
field = value
...