It seems Google offers a solution for this now
Saved State module for ViewModel
UI State is usually stored or referenced in ViewModel objects, not
activities; so using onSaveInstanceState() requires some boilerplate
that this module can handle for you.
When the module is set up, ViewModel objects receive a
SavedStateHandle object via its constructor. This is a key-value map
that will let you write and retrieve objects to and from the saved
state. These values will persist after the process is killed by the
system and remain available via the same object.
Setup
implementation 'androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-rc02'
(November 7, 2019)
Usage
In order to set up a ViewModel to receive a SavedStateHandle you need
to create them using a Factory that extends
AbstractSavedStateVMFactory.
SavedStateViewModel vm = new ViewModelProvider(this, new SavedStateVMFactory(this))
.get(SavedStateViewModel.class);
After that your ViewModel can have a constructor that receives a
SavedStateHandle:
public class SavedStateViewModel extends ViewModel {
private SavedStateHandle mState;
public SavedStateViewModel(SavedStateHandle savedStateHandle) {
mState = savedStateHandle;
}
...
}
Storing and retrieving values
The SavedStateHandle class has the methods you expect for a key-value map:
- get(String key)
- contains(String key)
- remove(String key)
- set(String key, T value)
- keys()
Application
. But I need a final confirmation before writing an angry blog post. – EndearStateProviders
class, from whereSavedStateProvider
can be accessed via static getter. But I couldn't find a component which will access those getters. If that class exists, it means that it has some purpose, which leads me to think that saving the state after process kill is something to be implemented in future releases. – Chaldean