Setting a key/value on a `SavedStateHandle` within...
# android
j
Setting a key/value on a
SavedStateHandle
within a (Fragment's) ViewModel's
onCleared()
does not appear to take effect (i.e. survive activity death). Setting it prior to
onCleared()
e.g. in
init {}
does successfully persist. Is that expected? I don't see that behavior documented anywhere, other than that onCleared comes after onDestroy.
i
onCleared()
means that ViewModel is never, ever coming back. There's no state saved for things never coming back
j
onCleared() is called if the activity is killed but may be resumed later via savedInstanceState. That specific instance of the viewmodel isn't coming back, but the data in SavedStateHandle does.
Granted I'm doing this from a Fragment not an Activity, so maybe there's some nuance I'm missing there, but: 1. I have a ViewModel accessed from my Fragment via
by viewModels()
2. that ViewModel injects a
SavedStateHandle
3. I call
set()
on that SavedStateHandle either in A)
init{}
or B)
onCleared()
4. Developer Settings -> don't keep activities is ON 5. Minimize app -> Activity destroyed 6. Return to app -> SavedStateHandle DOES contain my data in the case of A) and does NOT in the case of B)
i
Yeah,
onCleared()
is never going to work for your use case, since the state is saved at the activity level (which percolates down to every fragment and every ViewModel) before/right after
onStop()
(depending on your API level), which is well before
onCleared()
is called
Lifecycle 2.3 lets you just-in-time save data into your saved state, which would be the very last moment of time that saving is possible: https://stackoverflow.com/a/62800312/1676363
j
Thanks! I'll check that out.
149 Views