Register now for Android Dev Summit 2019!

Saved State module for ViewModel   Part of Android Jetpack.

As mentioned in the Saving UI States article, ViewModel objects can handle configuration changes so you don't need to worry about state in rotations or other cases. However, if you need to handle system-initiated process death, you may want to use onSaveInstanceState() as backup.

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 and usage

To import the Saved State module into your Android project, see the instructions for declaring dependencies in the Lifecycle release notes.

In order to set up a ViewModel to receive a SavedStateHandle you need to create them using a Factory that extends AbstractSavedStateVMFactory.

Kotlin

val vm = ViewModelProvider(this, SavedStateVMFactory(this))
        .get(SavedStateViewModel::class.java)

Java

SavedStateViewModel vm = new ViewModelProvider(this, new SavedStateVMFactory(this))
        .get(SavedStateViewModel.class);

After that your ViewModel can have a constructor that receives a SavedStateHandle:

Kotlin

class SavedStateViewModel(private val state: SavedStateHandle) : ViewModel() { ... }

Java


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()

Also, there is a special method: getLiveData(String key) that returns the value wrapped in a LiveData observable.

Acceptable classes

Type/Class Array support
double double[]
int int[]
long long[]
String String[]
byte byte[]
char char[]
CharSequence CharSequence[]
float float[]
Parcelable Parcelable[]
Serializable Serializable[]
short short[]
SparseArray
Binder
Bundle
ArrayList
Size (only in API 21+)
SizeF (only in API 21+)

Additional resources

For further information about the Saved State module for ViewModel, consult the following resources.

Codelabs