Sobes.tech
Junior — Middle

Kuidas toimub andmete salvestamine ViewModeli sees Android-rakendustes?

sobes.tech AI

Vastus AI-lt

In Android, ViewModel stores data that must survive configuration changes (e.g., screen rotation). It keeps the state in its fields, and when recreating an Activity or Fragment, the data remains accessible.

If you need to save data when the app 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.