In a Jetpack ViewModel, how does SavedStateHandle keep a half-filled car-rental booking form across process death, and what are its limits?
answer
- a key-value map bound to saved state
- constructor parameter, no factory needed
- getStateFlow versus getMutableStateFlow
- saved when the Activity stops
- IllegalArgumentException: one key, LiveData or MutableStateFlow
basics
~20 sSavedStateHandle is a key-value map the ViewModel receives in its constructor; it is written into the owner's saved state when the Activity stops and restored after process death. It holds only Bundle-compatible values, and loses them when the user removes the task.
solid answer
~40 sThe ViewModel takes a `SavedStateHandle` constructor parameter; the default factory supplies one bound to the owner's saved state, and a custom factory calls `createSavedStateHandle()`. I keep each form field under a key: `set` and `get`, or `getStateFlow(key, initialValue)` for a read-only stream and, since Lifecycle 2.9, `getMutableStateFlow(key, initialValue)` whose `value` writes straight back. After process death the restored value wins and the initial value is ignored. The limits: values must be Bundle-compatible types or `set` throws `IllegalArgumentException`; state is captured only when the host Activity stops; it is tied to the task, so swiping the app from Recents discards it; and it should hold small values such as ids and dates, not catalogs. On Android, `getMutableStateFlow` and `getLiveData` cannot share a key.
code
kotlin · 24 linesclass BookingViewModel(
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
// Restored after process death; "" only on a fresh start
val pickupDate: StateFlow<String> =
savedStateHandle.getStateFlow(KEY_PICKUP, "")
private val _carId =
savedStateHandle.getMutableStateFlow<String?>(KEY_CAR, null)
val carId: StateFlow<String?> = _carId.asStateFlow()
fun onPickupChosen(isoDate: String) {
savedStateHandle[KEY_PICKUP] = isoDate
}
fun onCarChosen(id: String) {
_carId.value = id // written back to the handle
}
private companion object {
const val KEY_PICKUP = "pickup_date"
const val KEY_CAR = "car_id"
}
}go deeper
Know that a ViewModel survives rotation but not process death, and that SavedStateHandle is the constructor parameter that brings small values back.
Explain set, get, getStateFlow and getMutableStateFlow, why the initial value is ignored after restore, which types fit, and that capture happens when the Activity stops.
Diagnose a form that is empty after process death: state kept only in fields, an unbound handle from the test constructor, a write made while stopped, or a LiveData and MutableStateFlow key clash.
Set what each screen may keep in the handle, small user input and ids, against what it reloads, and require a process-death check before release.
## Where the handle comes from A **`SavedStateHandle`** is a key-value map that a ViewModel receives through its constructor. Its values are written into the owner's saved state and come back when the system recreates the app after killing its process. A ViewModel gets one in two ways: - **No factory at all.** The default factory finds a constructor taking just `SavedStateHandle` (or `Application` plus `SavedStateHandle` for an `AndroidViewModel`) and passes in a handle bound to the owner. - **A custom factory.** It calls `CreationExtras.createSavedStateHandle()`, which binds the handle to the owner described by the extras. The public constructors, `SavedStateHandle()` and `SavedStateHandle(initialState)`, are marked `@VisibleForTesting` since Lifecycle 2.10. A handle built with them is not bound to any `SavedStateRegistryOwner`, so nothing saves or restores it: fine in a unit test, silent data loss in production. ## Reading and writing | API | Returns | How the saved value changes | |---|---|---| | `get(key)` / `set(key, value)` | `T?` from `get`; `set` returns nothing | `set` writes and updates any flow or LiveData for that key | | `getStateFlow(key, initialValue)` | `StateFlow<T>` | read-only; changed by `set` | | `getMutableStateFlow(key, initialValue)` | `MutableStateFlow<T>` | assigning `value` writes back (Lifecycle 2.9.0 and later) | | `getLiveData(key, initialValue)` | `MutableLiveData<T>` | `setValue` writes back | `contains`, `keys()` and `remove` complete the map. Two rules matter in practice: - **The initial value only fills an empty key.** If a value was restored after process death, `getStateFlow("pickup_date", "")` emits the restored date, not `""`. - **On Android, one key serves either LiveData or a `MutableStateFlow`, never both.** Whichever of `getLiveData` and `getMutableStateFlow` comes second for that key fails with `IllegalArgumentException` ("StateFlow and LiveData are mutually exclusive for the same key"). Calling `getStateFlow` on a key already backed by `getMutableStateFlow` returns that same flow as read-only. ## What it can hold Values travel in a `Bundle`, so `set` accepts the same types: primitives and their arrays, `String`, `CharSequence`, `Parcelable`, `Serializable`, `Bundle`, `ArrayList`, `SparseArray`, `Binder` and `null`. Anything else makes `set` throw `IllegalArgumentException` ("Can't put value with type ... into saved state"). The usual fixes: - annotate a small data class with `@Parcelize`, or store its id instead of the object; - for a `@Serializable` class, use the `saved` property delegate (Lifecycle 2.9 and later), which is lazy and saves nothing until the property is first accessed; - for a type you cannot change, register `setSavedStateProvider(key, provider)` and rebuild the object from the returned `Bundle`. One documented trap: an array of a custom `Parcelable` comes back as `Array<Parcelable>` after process death, so reading it directly as `Array<CustomParcelable>` throws `ClassCastException`. ## When it is saved and when it is lost 1. A `set` updates the in-memory map at once. 2. The handle's contents are captured into saved state when the host Activity is **stopped**. A write made while the Activity is already stopped is captured only after the next start and stop. 3. If the system kills the backgrounded process, the next launch recreates the Activity, the ViewModel and a handle filled with the captured values. 4. If the **user** ends the task, by swiping the app from Recents, force-stopping it or rebooting, the saved state is discarded and the handle starts empty. Saved state is also serialized, and the Android documentation warns against large or complex data in it: keep the minimum needed to rebuild the screen. ## In the booking flow The dates, the selected car id and the extras toggles are small, user-entered and expensive to lose, so each gets a key. The price list is reloaded in `viewModelScope` from the chosen dates and car, not saved. ## Diagnosing a form that comes back empty When a tester reports an empty booking form after the app was in the background for a while, the cause is usually one of these: - **The value lived only in a field or a plain `MutableStateFlow`.** A rotation kept it, because the ViewModel survived; process death did not, because nothing wrote it to the handle. - **The handle was built with `SavedStateHandle()`** in a hand-written factory instead of `createSavedStateHandle()`, so it was never bound to saved state. - **The write happened while the Activity was already stopped**, for example from a callback that finished in the background, and the process was killed before the next stop. - **Two code paths used different key strings** for the same field; a shared constant per key avoids it. - **The user removed the task** from Recents. That is expected behaviour, not a bug: saved state belongs to the task. To reproduce the path on a device, background the app, have the system kill its process, and return to it; the screen must rebuild itself from the handle alone.
- Why is a value set while the app sits in the background sometimes missing after process death?The handle is captured into saved state when the host Activity stops. A write made after that, while the Activity stays stopped, is not captured until the Activity is started and stopped again. If the system kills the process in between, the restored handle holds the value from the last stop, not the later write.
- Why does a handle built with SavedStateHandle() in production code lose its values?That constructor is `@VisibleForTesting`: the handle is not bound to the owner's `SavedStateRegistryOwner`, so nothing saves or restores it. Production code receives the handle from the default factory, or creates it with `createSavedStateHandle()` inside a `ViewModelProvider.Factory`.
- How do you keep an object SavedStateHandle cannot hold, such as a temporary File?Call `setSavedStateProvider(key, provider)`: the provider returns a `Bundle` with what is needed to rebuild the object, such as the file's path. On creation, read that `Bundle` back with `get<Bundle>(key)` and recreate the object from it.
- SavedStateHandle writes each set call to disk immediately.
- The initial value passed to getStateFlow overwrites the restored value.
- SavedStateHandle state survives the user swiping the app away from Recents.
- Any Kotlin data class can be stored with set without Parcelable or Serializable.
- getLiveData and getMutableStateFlow can share one key and stay in sync.
Assumes Lifecycle 2.11; getMutableStateFlow and its key exclusivity with getLiveData arrived in 2.9.0, and the handle's public constructors became @VisibleForTesting in 2.10.