Kuidas Android rakendab ViewModel'i oleku säilitamise mehhanismi konfiguratsiooni muutuste või elutsükli ajal?
sobes.tech AI
Vastus AI-lt
In Android, the ViewModel is designed to store and manage UI data considering the lifecycle. During configuration changes (e.g., screen rotation), the system destroys the Activity or Fragment, but the ViewModel remains preserved and is re-assigned to new instances.
This is achieved through ViewModelProvider, which binds the ViewModel to the component's lifecycle. The ViewModel stays in memory as long as it is associated with the owner's (Activity/Fragment) lifecycle. When a component is destroyed due to a configuration change, the ViewModel is not destroyed but reused in a new instance.
To save state within the ViewModel, you can use SavedStateHandle — a special object that allows saving and restoring data in case of process destruction or other situations beyond a simple 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)
}
This way, the ViewModel retains data in memory during configuration changes, and SavedStateHandle helps preserve state during more serious events, such as process destruction.