Junior — Middle
How is data saved inside a ViewModel in Android applications?
sobes.tech AI
Answer from AI
In Android, ViewModel stores data that should survive configuration changes (e.g., screen rotation). To do this, ViewModel keeps the state in its fields, and when the Activity or Fragment is recreated, the data remains accessible.
If you need to save data when the application is completely destroyed, you use SavedStateHandle — a special object that allows saving and restoring state.
Example of using ViewModel with SavedStateHandle:
class MyViewModel(private val state: SavedStateHandle) : ViewModel() {
var userName: String?
get() = state["userName"]
set(value) {
state["userName"] = value
}
}
Thus, data inside the ViewModel is stored in memory, and if necessary — in SavedStateHandle for restoration after process termination.