Sobes.tech
Junior — Middle

Kuidas saab ViewModeli sees andmeid salvestada hilisemaks kasutamiseks?

sobes.tech AI

Vastus AI-lt

To store data inside the ViewModel and reuse it, class fields of the ViewModel are usually used, which maintain the state throughout the lifecycle of the associated UI component.

If you need to save data when the process is destroyed (for example, during screen rotation or app closure), you can use SavedStateHandle — a special object that allows saving and restoring state.

Example of using SavedStateHandle:

class MyViewModel(private val state: SavedStateHandle) : ViewModel() {
    var userName: String?
        get() = state.get<String>("userName")
        set(value) = state.set("userName", value)
}

This way, data is automatically saved and restored, improving user experience and preventing data loss.