I have a screen that loads a bunch of requests and collects some data from the user on the same screen and an external WebView. Therefore, I have a ViewModel that contains these complex request objects (+ user input data). I need to persist this data through system-initiated process death, which SavedStateHandle
is designed for. But I don't want to persist this data in a database because it is only relevant to the current user experience.
I have integrated my ViewModels with Hilt and received SaveStateHandle
. Because I have some complex objects that are accessed/modified in several places in code I can't save them "on the go". I made them implement Parcelable
and just wanted to save them at once. Unfortunately, ViewModels don't have a lifecycle method like onSaveInstanceState()
.
Now, I have tried using onCleared()
which sounded like a ok place to write to the handle. But it turns out that all .set()
operations I perform there get lost (I'm testing this with developer options "Don't keep activities". When I use .set()
elsewhere, it does work). Because the ViewModel is not tied to the lifecycle of a single fragment/activity but rather to a NavGraph I can't call in from their onSaveInstanceState()
.
How/where can I properly persist my state in SaveStateHandle
?