skip to content

For Jetpack ViewModel and SavedStateHandle, what team rule would you set for which state is saved in the handle and which is reloaded after process death?

level: principalimportance: should knowfreq 33%

answer

  1. what the user typed versus what you fetched
  2. ids, not objects
  3. small, Bundle-friendly, serialized on save
  4. gone when the task is removed
  5. prove it with a process-death test

basics

~20 s

Save in SavedStateHandle only small user input and the ids needed to rebuild the screen; reload everything derivable from those ids through the data layer. Persist to disk whatever must survive the user closing the task, and test the rule with simulated process death.

solid answer

~50 s

My rule is: the handle holds what only the user knows and the keys to everything else. In a booking flow that is the chosen dates, the selected car id and the extras toggles; the car catalogue and prices are reloaded in `viewModelScope` from those values. The reasons are the handle's own limits: values must be Bundle types, they are serialized when the Activity stops and the docs warn that heavy serialization can drop frames, a copy is kept outside the process, and everything is discarded when the user removes the task. So a draft the user expects next week goes to disk, not the handle. I would back the rule with typed keys or the `saved` delegate, review for large objects, and a test that recreates the ViewModel through a process-death simulation, such as `ViewModelScenario.recreate()` or the Don't keep activities developer option.

go deeper

for a junior

Recall that ViewModel fields die with the process and SavedStateHandle brings back small saved values.

for a middle

Explain which types the handle accepts, when it captures state, and why the docs recommend ids over large objects.

for a senior

Review screens for input kept only in fields, catalogues saved in the handle, and drafts that should be on disk, and test them with recreation.

for a principal

Own the split between saved, reloaded and persisted state as an explicit team rule, weigh fidelity against serialization cost, and make it testable.

## The decision a lead owns Every ViewModel holds three kinds of state: **in-memory state** that dies with the process, **saved state** in its `SavedStateHandle`, and **persisted data** owned by the data layer. A rotation keeps all three. A system-initiated process death keeps only the last two. Which value goes where is a judgment call each screen makes, and without a team rule the answers drift: one screen saves a whole catalogue, the next saves nothing and comes back blank. There is no single correct split; the rule trades restore fidelity against cost and complexity. ## What the handle is good at, and what it costs | Property of `SavedStateHandle` | Consequence for the rule | |---|---| | values must be Bundle-compatible; `set` throws `IllegalArgumentException` otherwise | prefer primitives, strings and small `@Parcelize` or `@Serializable` types | | contents are captured when the host Activity stops | the latest edit made while stopped may be missing until the next stop | | saving serializes the data; the docs warn heavy serialization on the main thread can drop frames | large or deep objects cost every user, not only the ones whose process dies | | the system keeps a serialized copy outside the process | memory spent on saved state is paid even when it is never restored | | saved state is tied to the task | swiping from Recents, force stop or reboot discards it | The Android documentation's own guidance follows from this: keep the minimum needed to rebuild the screen, such as an id, and use local persistence for complex or large data. ## A rule that works 1. **Save user input that has not been submitted.** Dates, selections, toggles and text fields cannot be fetched again, so they go into the handle under named keys. 2. **Save ids, not objects.** Store the selected car's id, never the car with its photos and price table; the ViewModel reloads the object from the repository in `viewModelScope`. 3. **Reload everything derivable.** Lists, prices and server data come from the data layer; after process death they are fetched again, often from a local cache. 4. **Persist what must outlive the task.** A draft the user expects to find tomorrow is written to disk by the data layer, because the handle is gone once the task is removed. 5. **Leave UI-only details to the UI.** Scroll position or an expanded panel belongs to the UI's own saveable state, not the ViewModel. ## Trade-offs to weigh - **Restore fidelity versus cost.** Saving more brings the screen back exactly but makes every save heavier; reloading is cheap to write but shows a loading state after process death. Interaction-heavy forms usually justify saving input; read-only screens usually do not. - **Typed versus raw keys.** Raw string keys are simple but drift and collide. The `saved` property delegate, added in Lifecycle 2.9, keeps a `@Serializable` value under a key generated from the class and property names, and saves nothing until the property is first accessed; a team may prefer it for multi-field form state. - **Accessor consistency.** On Android a key served by `getLiveData` cannot also be served by `getMutableStateFlow`; a rule naming one accessor per screen avoids that `IllegalArgumentException` in mixed codebases. - **Who verifies it.** Process death rarely happens on a developer's device, so a rule without a test is a rule nobody checks. ## Enforcing it - In code review, flag non-trivial objects passed to `set`, catalogues in the handle, and screens whose ViewModel keeps user input only in fields. - In unit tests, build the ViewModel with `SavedStateHandle(mapOf(...))` to check that it rebuilds from saved values alone. - For a recreation test, the `ViewModelScenario` class from the `lifecycle-viewmodel-testing` artifact (Lifecycle 2.9) simulates process death with `recreate()`. - On a device, the Don't keep activities developer option destroys each Activity as soon as the user leaves it; returning then exercises the saved-state path without killing the process, so a process-level check still needs a real kill. A lead's job is less about the exact list than making the categories explicit, so each new screen answers the same three questions: what did the user enter, what ids rebuild the rest, and what must outlive the task.

  • Would you ever save a full list in SavedStateHandle instead of reloading it?
    Only when it is small and is itself user input, such as the extras the user ticked, or when reloading is impossible offline and the list is tiny. Data fetched from a server or a database is usually cheaper to reload than to serialize on every stop, and the handle is lost on task removal anyway.
  • How do you convince a team the rule matters when crashes from process death are rare?
    Show it: run the booking flow, background the app, kill the process, and return to an empty form. Then add a recreation test with `ViewModelScenario.recreate()` for each form screen, so the rule is checked on every build rather than argued in review.

  • Save the whole UI state object in SavedStateHandle so nothing ever needs reloading.
  • SavedStateHandle data survives the user swiping the app from Recents.
  • Process death is rare enough that ViewModel memory alone is fine for forms.
  • Bitmaps are fine in SavedStateHandle because Bitmap is Parcelable.
  • A value set while the app is in the background is always saved before a kill.

Assumes Lifecycle 2.11; the saved property delegate and the ViewModelScenario test class with recreate() arrived in 2.9.