class SavedStateHandle


A handle to saved state passed down to androidx.lifecycle.ViewModel. You should use SavedStateViewModelFactory if you want to receive this object in ViewModel's 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.

You can read a value from it via get or observe it via androidx.lifecycle.LiveData returned by getLiveData.

You can write a value to it via set or setting a value to androidx.lifecycle.MutableLiveData returned by getLiveData.

Summary

Public constructors

Creates a handle with the empty state.

SavedStateHandle(initialState: Map<StringAny?>)

Creates a handle with the given initial arguments.

Public functions

Unit

Clear any SavedStateProvider that was previously set via setSavedStateProvider.

operator Boolean
operator T?
@MainThread
<T : Any?> get(key: String)

Returns a value associated with the given key.

MutableLiveData<T>

Returns a androidx.lifecycle.LiveData that access data associated with the given key.

MutableLiveData<T>
@MainThread
<T : Any?> getLiveData(key: String, initialValue: T)

Returns a androidx.lifecycle.LiveData that access data associated with the given key.

StateFlow<T>
@MainThread
<T : Any?> getStateFlow(key: String, initialValue: T)

Returns a StateFlow that will emit the currently active value associated with the given key.

Set<String>

Returns all keys contained in this SavedStateHandle

T?
@MainThread
<T : Any?> remove(key: String)

Removes a value associated with the given key.

operator Unit
@MainThread
<T : Any?> set(key: String, value: T?)

Associate the given value with the key.

Unit

Set a SavedStateProvider that will have its state saved into this SavedStateHandle.

Extension functions

PropertyDelegateProvider<Any?, ReadOnlyProperty<Any?, T>>
@SavedStateHandleSaveableApi
<T : Any> SavedStateHandle.saveable(saver: Saver<T, Any>, init: () -> T)

Inter-opt between SavedStateHandle and Saver so that any state holder that is being saved via rememberSaveable with a custom Saver can also be saved with SavedStateHandle.

PropertyDelegateProvider<Any?, ReadWriteProperty<Any?, T>>
@SavedStateHandleSaveableApi
<T : Any, M : MutableState<T>> SavedStateHandle.saveable(
    stateSaver: Saver<T, Any>,
    init: () -> M
)

Inter-opt between SavedStateHandle and Saver so that any state holder that is being saved via rememberSaveable with a custom Saver can also be saved with SavedStateHandle.

T
@SavedStateHandleSaveableApi
<T : Any> SavedStateHandle.saveable(
    key: String,
    saver: Saver<T, Any>,
    init: () -> T
)

Inter-opt between SavedStateHandle and Saver so that any state holder that is being saved via rememberSaveable with a custom Saver can also be saved with SavedStateHandle.

MutableState<T>
@SavedStateHandleSaveableApi
<T : Any?> SavedStateHandle.saveable(
    key: String,
    stateSaver: Saver<T, Any>,
    init: () -> MutableState<T>
)

Inter-opt between SavedStateHandle and Saver so that any state holder that is being saved via rememberSaveable with a custom Saver can also be saved with SavedStateHandle.

Public constructors

SavedStateHandle

Added in 1.0.0
SavedStateHandle()

Creates a handle with the empty state.

SavedStateHandle

Added in 1.0.0
SavedStateHandle(initialState: Map<StringAny?>)

Creates a handle with the given initial arguments.

Parameters
initialState: Map<StringAny?>

initial arguments for the SavedStateHandle

Public functions

clearSavedStateProvider

Added in 2.3.0
@MainThread
fun clearSavedStateProvider(key: String): Unit

Clear any SavedStateProvider that was previously set via setSavedStateProvider.

Note: calling this method within SavedStateProvider.saveState is supported, but will only affect future state saving operations.

Parameters
key: String

a key previously used with setSavedStateProvider

contains

Added in 1.0.0
@MainThread
operator fun contains(key: String): Boolean
Parameters
key: String

The identifier for the value

Returns
Boolean

true if there is value associated with the given key.

get

Added in 1.0.0
@MainThread
operator fun <T : Any?> get(key: String): T?

Returns a value associated with the given key.

Note: If T is an Array of Parcelable classes, note that you should always use Array<Parcelable> and create a typed array from the result as going through process death and recreation (or using the Don't keep activities developer option) will result in the type information being lost, thus resulting in a ClassCastException if you directly try to assign the result to an Array<CustomParcelable> value.

val typedArray = savedStateHandle.get<Array<Parcelable>>("KEY").map {
it as CustomParcelable
}.toTypedArray()
Parameters
key: String

a key used to retrieve a value.

getLiveData

Added in 1.0.0
@MainThread
fun <T : Any?> getLiveData(key: String): MutableLiveData<T>

Returns a androidx.lifecycle.LiveData that access data associated with the given key.

Parameters
key: String

The identifier for the value

See also
getLiveData

getLiveData

Added in 1.0.0
@MainThread
fun <T : Any?> getLiveData(key: String, initialValue: T): MutableLiveData<T>

Returns a androidx.lifecycle.LiveData that access data associated with the given key.

`LiveData<String> liveData = savedStateHandle.get(KEY, "defaultValue");`

Keep in mind that LiveData can have null as a valid value. If the initialValue is null and the data does not already exist in the SavedStateHandle, the value of the returned LiveData will be set to null and observers will be notified. You can call getLiveData if you want to avoid dispatching null to observers.

`String defaultValue = ...; // nullable
LiveData<String> liveData;
if (defaultValue != null) {
liveData = savedStateHandle.getLiveData(KEY, defaultValue);
} else {
liveData = savedStateHandle.getLiveData(KEY);
}`

Note: If T is an Array of Parcelable classes, note that you should always use Array<Parcelable> and create a typed array from the result as going through process death and recreation (or using the Don't keep activities developer option) will result in the type information being lost, thus resulting in a ClassCastException if you directly try to observe the result as an Array<CustomParcelable>.

val typedArrayLiveData = savedStateHandle.getLiveData<Array<Parcelable>>(
"KEY"
).map { array ->
// Convert the Array<Parcelable> to an Array<CustomParcelable>
array.map { it as CustomParcelable }.toTypedArray()
}
Parameters
key: String

The identifier for the value

initialValue: T

If no value exists with the given key, a new one is created with the given initialValue. Note that passing null will create a LiveData with null value.

getStateFlow

Added in 2.5.0
@MainThread
fun <T : Any?> getStateFlow(key: String, initialValue: T): StateFlow<T>

Returns a StateFlow that will emit the currently active value associated with the given key.

val flow = savedStateHandle.getStateFlow(KEY, "defaultValue")

Since this is a StateFlow there will always be a value available which, is why an initial value must be provided. The value of this flow is changed by making a call to set, passing in the key that references this flow.

If there is already a value associated with the given key, the initial value will be ignored.

Note: If T is an Array of Parcelable classes, note that you should always use Array<Parcelable> and create a typed array from the result as going through process death and recreation (or using the Don't keep activities developer option) will result in the type information being lost, thus resulting in a ClassCastException if you directly try to collect the result as an Array<CustomParcelable>.

val typedArrayFlow = savedStateHandle.getStateFlow<Array<Parcelable>>(
"KEY"
).map { array ->
// Convert the Array<Parcelable> to an Array<CustomParcelable>
array.map { it as CustomParcelable }.toTypedArray()
}
Parameters
key: String

The identifier for the flow

initialValue: T

If no value exists with the given key, a new one is created with the given initialValue.

keys

Added in 1.0.0
@MainThread
fun keys(): Set<String>

Returns all keys contained in this SavedStateHandle

Returned set contains all keys: keys used to get LiveData-s, to set SavedStateProviders and keys used in regular set.

remove

Added in 1.0.0
@MainThread
fun <T : Any?> remove(key: String): T?

Removes a value associated with the given key. If there is a LiveData and/or StateFlow associated with the given key, they will be removed as well.

All changes to androidx.lifecycle.LiveDatas or StateFlows previously returned by SavedStateHandle.getLiveData or getStateFlow won't be reflected in the saved state. Also that LiveData or StateFlow won't receive any updates about new values associated by the given key.

Parameters
key: String

a key

Returns
T?

a value that was previously associated with the given key.

set

Added in 1.0.0
@MainThread
operator fun <T : Any?> set(key: String, value: T?): Unit

Associate the given value with the key. The value must have a type that could be stored in android.os.Bundle

This also sets values for any active LiveDatas or Flows.

Parameters
key: String

a key used to associate with the given value.

value: T?

object of any type that can be accepted by Bundle.

Throws
kotlin.IllegalArgumentException

value cannot be saved in saved state

setSavedStateProvider

Added in 2.3.0
@MainThread
fun setSavedStateProvider(
    key: String,
    provider: SavedStateRegistry.SavedStateProvider
): Unit

Set a SavedStateProvider that will have its state saved into this SavedStateHandle. This provides a mechanism to lazily provide the Bundle of saved state for the given key.

Calls to get with this same key will return the previously saved state as a Bundle if it exists.

Bundle previousState = savedStateHandle.get("custom_object");
if (previousState != null) {
// Convert the previousState into your custom object
}
savedStateHandle.setSavedStateProvider("custom_object", () -> {
Bundle savedState = new Bundle();
// Put your custom object into the Bundle, doing any conversion required
return savedState;
});

Note: calling this method within SavedStateProvider.saveState is supported, but will only affect future state saving operations.

Parameters
key: String

a key which will populated with a Bundle produced by the provider

provider: SavedStateRegistry.SavedStateProvider

a SavedStateProvider which will receive a callback to SavedStateProvider.saveState when the state should be saved

Extension functions

@SavedStateHandleSaveableApi
fun <T : Any> SavedStateHandle.saveable(
    saver: Saver<T, Any> = autoSaver(),
    init: () -> T
): PropertyDelegateProvider<Any?, ReadOnlyProperty<Any?, T>>

Inter-opt between SavedStateHandle and Saver so that any state holder that is being saved via rememberSaveable with a custom Saver can also be saved with SavedStateHandle.

The key is automatically retrieved as the name of the property this delegate is being used to create.

The returned state T should be the only way that a value is saved or restored from the SavedStateHandle with the automatic key.

Using the same key again with another SavedStateHandle method is not supported, as values won't cross-set or communicate updates.

import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.toMutableStateList
import androidx.compose.runtime.toMutableStateMap
import androidx.lifecycle.viewmodel.compose.saveable

/**
 * A simple item that is not inherently [Parcelable]
 */
data class Item(
    val id: UUID,
    val value: String
)

@OptIn(SavedStateHandleSaveableApi::class)
class SnapshotStateViewModel(handle: SavedStateHandle) : ViewModel() {

    /**
     * A snapshot-backed [MutableList] of a list of items, persisted by the [SavedStateHandle].
     * The size of this set must remain small in expectation, since the maximum size of saved
     * instance state space is limited.
     */
    private val items: MutableList<Item> by handle.saveable(
        saver = listSaver(
            save = {
                it.map { item ->
                    listOf(item.id.toString(), item.value)
                }
            },
            restore = {
                it.map { saved ->
                    Item(
                        id = UUID.fromString(saved[0]),
                        value = saved[1]
                    )
                }.toMutableStateList()
            }
        )
    ) {
        mutableStateListOf()
    }

    /**
     * A snapshot-backed [MutableMap] representing a set of selected item ids, persisted by the
     * [SavedStateHandle]. A [MutableSet] is approximated by ignoring the keys.
     * The size of this set must remain small in expectation, since the maximum size of saved
     * instance state space is limited.
     */
    private val selectedItemIds: MutableMap<UUID, Unit> by handle.saveable(
        saver = listSaver(
            save = { it.keys.map(UUID::toString) },
            restore = { it.map(UUID::fromString).map { id -> id to Unit }.toMutableStateMap() }
        )
    ) {
        mutableStateMapOf()
    }

    /**
     * A snapshot-backed flag representing where selections are enabled, persisted by the
     * [SavedStateHandle].
     */
    var areSelectionsEnabled by handle.saveable { mutableStateOf(true) }

    /**
     * A list of items paired with a selection state.
     */
    val selectedItems: List<Pair<Item, Boolean>> get() =
        items.map { it to (it.id in selectedItemIds) }

    /**
     * Updates the selection state for the item with [id] to [selected].
     */
    fun selectItem(id: UUID, selected: Boolean) {
        if (selected) {
            selectedItemIds[id] = Unit
        } else {
            selectedItemIds.remove(id)
        }
    }

    /**
     * Adds an item with the given [value].
     */
    fun addItem(value: String) {
        items.add(Item(UUID.randomUUID(), value))
    }
}
@SavedStateHandleSaveableApi
fun <T : Any, M : MutableState<T>> SavedStateHandle.saveable(
    stateSaver: Saver<T, Any> = autoSaver(),
    init: () -> M
): PropertyDelegateProvider<Any?, ReadWriteProperty<Any?, T>>

Inter-opt between SavedStateHandle and Saver so that any state holder that is being saved via rememberSaveable with a custom Saver can also be saved with SavedStateHandle.

The key is automatically retrieved as the name of the property this delegate is being used to create.

The delegated MutableState should be the only way that a value is saved or restored from the SavedStateHandle with the automatic key.

Using the same key again with another SavedStateHandle method is not supported, as values won't cross-set or communicate updates.

Use this overload to allow delegating to a mutable state just like you can with rememberSaveable:

var value by savedStateHandle.saveable { mutableStateOf("initialValue") }
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.toMutableStateList
import androidx.compose.runtime.toMutableStateMap
import androidx.lifecycle.viewmodel.compose.saveable

/**
 * A simple item that is not inherently [Parcelable]
 */
data class Item(
    val id: UUID,
    val value: String
)

@OptIn(SavedStateHandleSaveableApi::class)
class SnapshotStateViewModel(handle: SavedStateHandle) : ViewModel() {

    /**
     * A snapshot-backed [MutableList] of a list of items, persisted by the [SavedStateHandle].
     * The size of this set must remain small in expectation, since the maximum size of saved
     * instance state space is limited.
     */
    private val items: MutableList<Item> by handle.saveable(
        saver = listSaver(
            save = {
                it.map { item ->
                    listOf(item.id.toString(), item.value)
                }
            },
            restore = {
                it.map { saved ->
                    Item(
                        id = UUID.fromString(saved[0]),
                        value = saved[1]
                    )
                }.toMutableStateList()
            }
        )
    ) {
        mutableStateListOf()
    }

    /**
     * A snapshot-backed [MutableMap] representing a set of selected item ids, persisted by the
     * [SavedStateHandle]. A [MutableSet] is approximated by ignoring the keys.
     * The size of this set must remain small in expectation, since the maximum size of saved
     * instance state space is limited.
     */
    private val selectedItemIds: MutableMap<UUID, Unit> by handle.saveable(
        saver = listSaver(
            save = { it.keys.map(UUID::toString) },
            restore = { it.map(UUID::fromString).map { id -> id to Unit }.toMutableStateMap() }
        )
    ) {
        mutableStateMapOf()
    }

    /**
     * A snapshot-backed flag representing where selections are enabled, persisted by the
     * [SavedStateHandle].
     */
    var areSelectionsEnabled by handle.saveable { mutableStateOf(true) }

    /**
     * A list of items paired with a selection state.
     */
    val selectedItems: List<Pair<Item, Boolean>> get() =
        items.map { it to (it.id in selectedItemIds) }

    /**
     * Updates the selection state for the item with [id] to [selected].
     */
    fun selectItem(id: UUID, selected: Boolean) {
        if (selected) {
            selectedItemIds[id] = Unit
        } else {
            selectedItemIds.remove(id)
        }
    }

    /**
     * Adds an item with the given [value].
     */
    fun addItem(value: String) {
        items.add(Item(UUID.randomUUID(), value))
    }
}
@SavedStateHandleSaveableApi
fun <T : Any> SavedStateHandle.saveable(
    key: String,
    saver: Saver<T, Any> = autoSaver(),
    init: () -> T
): T

Inter-opt between SavedStateHandle and Saver so that any state holder that is being saved via rememberSaveable with a custom Saver can also be saved with SavedStateHandle.

The returned state T should be the only way that a value is saved or restored from the SavedStateHandle with the given key.

Using the same key again with another SavedStateHandle method is not supported, as values won't cross-set or communicate updates.

import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.toMutableStateList
import androidx.compose.runtime.toMutableStateMap
import androidx.lifecycle.viewmodel.compose.saveable

/**
 * A simple item that is not inherently [Parcelable]
 */
data class Item(
    val id: UUID,
    val value: String
)

@OptIn(SavedStateHandleSaveableApi::class)
class SnapshotStateViewModel(handle: SavedStateHandle) : ViewModel() {

    /**
     * A snapshot-backed [MutableList] of a list of items, persisted by the [SavedStateHandle].
     * The size of this set must remain small in expectation, since the maximum size of saved
     * instance state space is limited.
     */
    private val items: MutableList<Item> = handle.saveable(
        key = "items",
        saver = listSaver(
            save = {
                it.map { item ->
                    listOf(item.id.toString(), item.value)
                }
            },
            restore = {
                it.map { saved ->
                    Item(
                        id = UUID.fromString(saved[0]),
                        value = saved[1]
                    )
                }.toMutableStateList()
            }
        )
    ) {
        mutableStateListOf()
    }

    /**
     * A snapshot-backed [MutableMap] representing a set of selected item ids, persisted by the
     * [SavedStateHandle]. A [MutableSet] is approximated by ignoring the keys.
     * The size of this set must remain small in expectation, since the maximum size of saved
     * instance state space is limited.
     */
    private val selectedItemIds: MutableMap<UUID, Unit> = handle.saveable(
        key = "selectedItemIds",
        saver = listSaver(
            save = { it.keys.map(UUID::toString) },
            restore = { it.map(UUID::fromString).map { id -> id to Unit }.toMutableStateMap() }
        )
    ) {
        mutableStateMapOf()
    }

    /**
     * A snapshot-backed flag representing where selections are enabled, persisted by the
     * [SavedStateHandle].
     */
    var areSelectionsEnabled by handle.saveable("areSelectionsEnabled") {
        mutableStateOf(true)
    }

    /**
     * A list of items paired with a selection state.
     */
    val selectedItems: List<Pair<Item, Boolean>> get() =
        items.map { it to (it.id in selectedItemIds) }

    /**
     * Updates the selection state for the item with [id] to [selected].
     */
    fun selectItem(id: UUID, selected: Boolean) {
        if (selected) {
            selectedItemIds[id] = Unit
        } else {
            selectedItemIds.remove(id)
        }
    }

    /**
     * Adds an item with the given [value].
     */
    fun addItem(value: String) {
        items.add(Item(UUID.randomUUID(), value))
    }
}
@SavedStateHandleSaveableApi
fun <T : Any?> SavedStateHandle.saveable(
    key: String,
    stateSaver: Saver<T, Any>,
    init: () -> MutableState<T>
): MutableState<T>

Inter-opt between SavedStateHandle and Saver so that any state holder that is being saved via rememberSaveable with a custom Saver can also be saved with SavedStateHandle.

The returned MutableState should be the only way that a value is saved or restored from the SavedStateHandle with the given key.

Using the same key again with another SavedStateHandle method is not supported, as values won't cross-set or communicate updates.

Use this overload if you remember a mutable state with a type which can't be stored in the Bundle so you have to provide a custom saver object.

import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.toMutableStateList
import androidx.compose.runtime.toMutableStateMap
import androidx.lifecycle.viewmodel.compose.saveable

/**
 * A simple item that is not inherently [Parcelable]
 */
data class Item(
    val id: UUID,
    val value: String
)

@OptIn(SavedStateHandleSaveableApi::class)
class SnapshotStateViewModel(handle: SavedStateHandle) : ViewModel() {

    /**
     * A snapshot-backed [MutableList] of a list of items, persisted by the [SavedStateHandle].
     * The size of this set must remain small in expectation, since the maximum size of saved
     * instance state space is limited.
     */
    private val items: MutableList<Item> = handle.saveable(
        key = "items",
        saver = listSaver(
            save = {
                it.map { item ->
                    listOf(item.id.toString(), item.value)
                }
            },
            restore = {
                it.map { saved ->
                    Item(
                        id = UUID.fromString(saved[0]),
                        value = saved[1]
                    )
                }.toMutableStateList()
            }
        )
    ) {
        mutableStateListOf()
    }

    /**
     * A snapshot-backed [MutableMap] representing a set of selected item ids, persisted by the
     * [SavedStateHandle]. A [MutableSet] is approximated by ignoring the keys.
     * The size of this set must remain small in expectation, since the maximum size of saved
     * instance state space is limited.
     */
    private val selectedItemIds: MutableMap<UUID, Unit> = handle.saveable(
        key = "selectedItemIds",
        saver = listSaver(
            save = { it.keys.map(UUID::toString) },
            restore = { it.map(UUID::fromString).map { id -> id to Unit }.toMutableStateMap() }
        )
    ) {
        mutableStateMapOf()
    }

    /**
     * A snapshot-backed flag representing where selections are enabled, persisted by the
     * [SavedStateHandle].
     */
    var areSelectionsEnabled by handle.saveable("areSelectionsEnabled") {
        mutableStateOf(true)
    }

    /**
     * A list of items paired with a selection state.
     */
    val selectedItems: List<Pair<Item, Boolean>> get() =
        items.map { it to (it.id in selectedItemIds) }

    /**
     * Updates the selection state for the item with [id] to [selected].
     */
    fun selectItem(id: UUID, selected: Boolean) {
        if (selected) {
            selectedItemIds[id] = Unit
        } else {
            selectedItemIds.remove(id)
        }
    }

    /**
     * Adds an item with the given [value].
     */
    fun addItem(value: String) {
        items.add(Item(UUID.randomUUID(), value))
    }
}