[Android] Released ViewModel-SavedState-ktx, an easy-to-use library for SavedStateHandle

Takumi WADA
ViewModel-SavedState-ktx
3 min readOct 5, 2019
ViewModel-SavedState-ktx 1.0.0-alpha05

# What is ViewModel-SavedState-ktx

A library that hides the SavedStateHandle of ViewModel-SavedState so that it can be easily handled by Delegated Property.

## What is ViewModel-SavedState

Since the ViewModel is destroyed when the process is killed, there is no state left when the Activity is regenerated. Therefore, if you want to keep the state, you need to save the state with onSavedInstanceState. This is a situation where you need to use onSavedInstanceState to handle process kills even though you have separated the state from the activity.

ViewModel-SavedState is a Jetpack library that makes it easy to manage state with ViewModel without using onSavedInstanceState by using SavedStateHandle.

The current latest version is 1.0.0-alpha05.
https://developer.android.com/jetpack/androidx/releases/lifecycle#viewmodel-savedstate-1.0.0-alpha05

## What is SavedStateHandle

SavedStateHandle can hold values ​​that can be put into a Bundle and can be treated like a HashMap. You can also get LiveData where changes are automatically saved.

class SampleViewModel(
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
companion object {
private const val KEY_TEXT = "text"
}

var text: String?
get() = savedStateHandle.get(KEY_TEXT)
set(value) {
savedStateHandle.set(KEY_TEXT, value)
}
val textLiveData: LiveData<String> = savedStateHandle.getLiveData(KEY_TEXT)
}

# What is nice about ViewModel-SavedState-ktx

In Kotlin’s Delegated Property you can write:

class SampleViewModel(
savedStateHandle: SavedStateHandle
) : SavedStateViewModel(savedStateHandle) {
companion object {
private const val KEY_TEXT = "text"
}
var text: String by savedStateProperty(KEY_TEXT)
val textLiveData: LiveData<String> by savedStateLiveData(KEY_TEXT)
}

The major change is SavedStateHandle. SavedStateHandle only exists in the constructor and you don’t need to be aware of it when you use it.

The following 4 points are minor changes.
1. Inherit SavedStateViewModel
2. Pass SavedStateHandle to SavedStateViewModel constructor
3. Declare the property whose state you want to keep with savedStateProperty
4. If you want LiveData, declare it by savedStateLiveData

Now you can completely abstract access to SavedStateHandle. This can be done without being aware of saving the state.

# Use ViewModel-SavedState-ktx

Add the following to build.gradle:

repositories {
maven { url "https://www.jitpack.io" }
}
dependencies {
implementation 'com.github.wada811:ViewModel-SavedState-ktx:1.0.0-alpha05'
}

The version is 1.0.0-alpha05, but if you think that ViewModel-SavedState is Production Ready because it is only adapted to the version of ViewModel-SavedState, ViewModel-SavedState-ktx can also be said to be Production Ready.

# References

--

--