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
Ian Lake
01/15/2021, 7:21 PM
onCleared()
means that ViewModel is never, ever coming back. There's no state saved for things never coming back
j
jeff
01/15/2021, 7:28 PM
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.
jeff
01/15/2021, 7:37 PM
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
Ian Lake
01/15/2021, 9:50 PM
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
Ian Lake
01/15/2021, 9:51 PM
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