How does Android implement the mechanism of saving ViewModel state during configuration changes or lifecycle events?
sobes.tech AI
Answer from AI
In Android, ViewModel is designed to store and manage UI data considering the lifecycle. When a configuration change occurs (for example, screen rotation), the system destroys the Activity or Fragment, but the ViewModel persists and is re-provided to new instances.
This is achieved through ViewModelProvider, which binds the ViewModel to the component's lifecycle. The ViewModel is stored in memory as long as it is associated with the lifecycle owner (Activity/Fragment). When the component is destroyed due to a configuration change, the ViewModel is not destroyed but reused by a new instance.
To save state within a ViewModel, you can use SavedStateHandle — a special object that allows saving and restoring data when the process is killed or in other situations beyond a normal configuration change.
Example of using SavedStateHandle:
class MyViewModel(private val state: SavedStateHandle) : ViewModel() {
var counter: Int
get() = state.get<Int>("counter") ?: 0
set(value) = state.set("counter", value)
}
Thus, the ViewModel saves data in memory during configuration changes, and SavedStateHandle helps preserve the state during more serious events, such as process termination.