Has anyone encountered data loss for state variabl...
# compose-android
a
Has anyone encountered data loss for state variables on a physical device? I used my phone with other apps and, upon resuming to the app in development, it correctly showed the right screen that was previously opened, however, all data was lost and the app was rendered unusable. It seems ViewModel
mutableStateOf(...)
variables were reset to default, initial(ized), values. This is the first time it ever happened to me. Any clues on how to address it without introducing
init
in ViewModels?
s
You just experienced what process death looks like. This is a very normal thing to happen, and it happens all the time. It's the entire reason why the architecture guides always talk about working with a single source of truth, using your persistent data layer as your SSOT etc. Here are some relevant links. https://developer.android.com/topic/libraries/architecture/saving-states#local https://developer.android.com/guide/topics/resources/runtime-changes#user-expectations
thank you color 1
t
You also may look at the lifecycle of view models. They do not live for ever.
s
Indeed, a process death does mean that you will get a whole new instance of your ViewModel. Which is exactly why you saw the mutable states "re-initialize" as you said yourself. What would persist is if you saved anything in the SavedStateHandle (hence the name).
i
Note there are a number of
savedStateHandle.saveable
extensions available for backing your MutableState with the
SavedStateHandle
so that it can survive configuration change - it uses the same
Saver
APIs that
rememberSaveable
uses: https://developer.android.com/reference/kotlin/androidx/lifecycle/viewmodel/compose/package-summary?hl=en#extension-functions
thank you color 1