SavedStateHandle

Lifecycle and app components Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Fill the blank

Expose the saved query as a StateFlow.

class SearchViewModel(private val handle: SavedStateHandle) : ViewModel() {
    val query: StateFlow<String> = handle.____("query", "")
    fun onQuery(q: String) { handle["query"] = q }
}
Options
Hint 1 of 1

You want a stream that updates when the value is set.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A getStateFlow

Correct. It returns a StateFlow backed by the saved value.

Why not the others?
  • B getLiveData. That returns LiveData, not a StateFlow.
  • C get. get returns the current value once, not a stream.
  • D remove. That deletes the key.

30-second answer

SavedStateHandle is a key-value map passed into a ViewModel that is saved into the Activity's saved state and restored after process death. Put small values that let you rebuild the screen: IDs, the current step, filter choices, unsaved input. It also carries navigation arguments into the destination's ViewModel.

Practise saying it · 30 s. No recording, just a timer

Explain SavedStateHandle.

Say your answer out loud, then check which of these points you covered:

  • Saved key-value map for a ViewModel
  • Survives process death
  • Store IDs and small input
  • Carries navigation args

Deep dive

getStateFlow(key, default) exposes a value as a StateFlow that updates when you set it.

With Hilt, a @HiltViewModel gets SavedStateHandle injected automatically.

Values must be Bundle types or Parcelable; keep the total small, because the Binder transaction limit is about 1 MB shared by the whole process.

Navigation Compose's toRoute<T>() reads typed arguments from it.

Common mistakes

  • Storing a list of loaded items in it.
  • Writing to it from many places with different keys and types.
  • Using it for data that belongs in a database.

Senior take & follow-ups

Say what not to store, with the size limit, and connect it to process death.

Follow-up questions

Think of your answer first, then open the hint.

  1. How does a destination read its navigation argument?

    Show hint

    savedStateHandle.toRoute<Route>(), or by key.

  2. What happens if the saved state is too big?

    Show hint

    TransactionTooLargeException when the Activity stops.

Suggest a fix if something here is wrong or out of date.