SavedStateHandle and process death

Learn how to handle Android process death and configuration changes using SavedStateHandle in a ViewModel to preserve critical UI state in Kotlin. About 20 minutes.

Why it matters

  • Configuration changes are easy to test, but system-initiated process death silently wipes user progress, and it only happens on real devices under memory pressure.
  • Interviewers use this to see whether you understand the process lifecycle, not just the Activity lifecycle: what the ViewModel survives and what it does not.
  • Putting too much in saved state crashes the app with TransactionTooLargeException; putting too little loses the user's place.
  • SavedStateHandle sits between in-memory ViewModel state and persistent storage such as Room or DataStore, and you need to know which job belongs to which.

The simple explanation

  • You are writing a book on a chalkboard.
  • A configuration change is like turning the chalkboard over; the writing is still there when you flip it back.
  • Process death is like a sudden rainstorm that washes the chalkboard clean.
  • SavedStateHandle is like a small notebook where you jot down the current page number and the last sentence written so you can rewrite it after the rain stops.

Android can kill your app's process to reclaim memory while your app is in the background. When the user returns, the system starts a new process, recreates the Activity and creates a new ViewModel instance. Everything that lived only in memory, including the old ViewModel's properties and any singletons, is gone. This is system-initiated process death.

SavedStateHandle is a key-value map that the ViewModel receives in its constructor (the default ViewModel factory, Hilt and createSavedStateHandle() all provide it). Its contents are written into the saved-state Bundle of the screen when the system saves instance state, and given back to the new ViewModel after process death.

SituationViewModel propertySavedStateHandleDisk / database
Configuration changeSurvivesSurvivesSurvives
System-initiated process deathLostSurvivesSurvives
User presses Back to close the screen, or swipes the app away in RecentsLostLostSurvives
Device rebootLostLostSurvives
Size and typesLimited by memory, any objectSmall values of Bundle types: primitives, String, Parcelable, Serializable, arrays and lists of theseLimited by disk

Use getStateFlow(key, initialValue) to read a value as a StateFlow; setting savedStateHandle[key] = value updates that flow. The handle stays the single source of truth for that value.

Crucial rule: Only store small values you need to rebuild the screen (IDs, a search query, a selected tab, a scroll position) in SavedStateHandle. Large objects, lists of loaded data and bitmaps belong in a database or file and are reloaded using those small values. Saved state is sent to the system through Binder, whose transaction buffer is about 1 MB shared by the whole process, so a large saved state crashes with TransactionTooLargeException when the app goes to the background.

Coming back after process death
Coming back after process death The app goes to the background and the system kills the process, so the Activity and ViewModel are gone. The user returns. The system creates a new Activity and a new ViewModel, and restores the saved-state Bundle into its SavedStateHandle, so the ViewModel reads back the small values it saved. Activity and ViewModel are gone LEAVES THE APP KILLS THE PROCESS RETURNS NEW ACTIVITY + VM RESTORE BUNDLE SAVED VALUES User switches apps System low memory New ViewModel fresh instance Saved state SavedStateHandle
The old ViewModel is gone, but the values written to SavedStateHandle come back from the saved-state Bundle.

Notes

  • Process death is different from a configuration change: after process death you get a new ViewModel instance, not the old one.
  • Saved state is only restored when the system killed the process. If the user closes the screen with Back or swipes the app away in Recents, it is discarded on purpose.
  • Use SavedStateHandle to restore essential identifiers like userId or productId, and user input that is hard to re-enter.
  • Avoid storing large collections or bitmaps; store an id or a URI and reload the data from a database or file.
  • Use getStateFlow to bring a saved value into your UiState stream.
  • Values must be types a Bundle can hold. Setting another type throws an IllegalArgumentException.
  • Navigation arguments are also available in the destination ViewModel's SavedStateHandle.
  • In Compose, state that belongs to the UI element itself, such as a text field's contents or an expanded flag, can use rememberSaveable, which goes into the same saved-state Bundle.
  • In unit tests, create a real SavedStateHandle(mapOf("key" to value)) and pass it to the ViewModel; no Android device is needed.
  • To test real process death: put the app in the background, run adb shell am kill <package>, then reopen it from Recents.

Code example

This ViewModel keeps a search query across process death and reloads the results from it.

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.stateIn
 
interface SearchRepository {
    suspend fun search(query: String): List<String> // main-safe
}
 
data class SearchUiState(
    val query: String = "",
    val results: List<String> = emptyList(),
)
 
@OptIn(ExperimentalCoroutinesApi::class)
class SearchViewModel(
    private val savedStateHandle: SavedStateHandle,
    private val repository: SearchRepository,
) : ViewModel() {
 
    companion object {
        private const val KEY_QUERY = "search_query"
    }
 
    // Only the small query is saved. The results are reloaded from it.
    private val query: StateFlow<String> = savedStateHandle.getStateFlow(KEY_QUERY, "")
 
    val uiState: StateFlow<SearchUiState> = query
        .mapLatest { q ->
            SearchUiState(query = q, results = if (q.isBlank()) emptyList() else repository.search(q))
        }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = SearchUiState(query = query.value), // the restored query, from the first frame
        )
 
    fun updateQuery(newQuery: String) {
        savedStateHandle[KEY_QUERY] = newQuery // also updates the query StateFlow
    }
}
  • getStateFlow returns a read-only StateFlow backed by the handle. Writing the key with savedStateHandle[KEY_QUERY] = ... updates it.
  • The results list is never saved. After process death, the restored query flows through mapLatest and the results are fetched again (from a Room cache in a real app, so it is fast).
  • The initial value uses query.value, so the restored query appears in the first frame instead of an empty string.
  • WhileSubscribed(5_000) keeps the flow running through a rotation and stops it 5 s after the screen stops being collected.

Run the idea in plain Kotlin

A small model of the three cases: rotation keeps the same ViewModel, process death rebuilds it from the saved map, and the user closing the screen discards everything.

class FakeSavedStateHandle(initial: Map<String, Any?> = emptyMap()) {
  private val values = initial.toMutableMap()

  @Suppress("UNCHECKED_CAST")
  operator fun <T> get(key: String): T? = values[key] as T?

  operator fun set(key: String, value: Any?) {
      values[key] = value
  }

  // What the system keeps in the saved-state Bundle
  fun savedState(): Map<String, Any?> = values.toMap()
}

class SearchViewModel(val handle: FakeSavedStateHandle) {
  var results: List<String> = emptyList() // in memory only
      private set

  val query: String get() = handle["query"] ?: ""

  fun onQueryChanged(q: String) {
      handle["query"] = q
      results = listOf(q + " 1", q + " 2")
  }
}

fun main() {
  var vm = SearchViewModel(FakeSavedStateHandle())
  vm.onQueryChanged("compose")
  println("before:              query=" + vm.query + " results=" + vm.results)

  // Rotation: the same ViewModel instance is handed to the new Activity
  println("after rotation:      query=" + vm.query + " results=" + vm.results)

  // Background, then process death: only the saved state is left
  val bundle = vm.handle.savedState()
  vm = SearchViewModel(FakeSavedStateHandle(bundle))
  println("after process death: query=" + vm.query + " results=" + vm.results)

  // The user presses Back and opens the screen again: saved state was discarded
  vm = SearchViewModel(FakeSavedStateHandle())
  println("after Back, reopen:  query=" + vm.query + " results=" + vm.results)
}

Expected output:

before:              query=compose results=[compose 1, compose 2]
after rotation:      query=compose results=[compose 1, compose 2]
after process death: query=compose results=[]
after Back, reopen:  query= results=[]
  • After process death the query is back but the results are not. The real ViewModel reloads them from the query, as in the example above.

In production

The Lost Multi-Select
  • Users reported that the photos they had selected for sharing disappeared after they switched to another app to check a message.
  • The ViewModel kept the selected photo ids only in a private MutableStateFlow<Set<Long>>.
  • On low-memory devices the system killed the process in the background. On return, the screen was restored but the new ViewModel started with an empty selection.
The fix
  • Moved the selected ids into SavedStateHandle (a LongArray is a Bundle type) and read them with getStateFlow.
  • Reproduced and verified by backgrounding the app and running adb shell am kill <package>, then reopening it from Recents.
  • Added a unit test that creates the ViewModel with SavedStateHandle(mapOf("selected" to longArrayOf(1, 2))) and asserts the selection.
The Crash on Attach
  • The app crashed with TransactionTooLargeException when users of a long registration form opened the camera to attach an ID photo.
  • The team saved the entire UserRegistration object, including the image bytes of earlier attachments, into SavedStateHandle.
  • Opening the camera stopped the Activity, saved state was sent to the system, and the Bundle was too large for the Binder transaction.
The fix
  • Measured the saved-state size per screen with the TooLargeTool library in a debug build.
  • Saved form drafts to Room as the user typed, and kept only the registrationId and the current step in SavedStateHandle. Attachments are stored as files and referenced by URI.
  • On restoration, the ViewModel loads the draft from Room using that id.

Common mistakes

  • Storing large Bitmaps or loaded lists in SavedStateHandle. It causes TransactionTooLargeException when the app goes to the background. Store the file URI or the ids instead.
  • Using SavedStateHandle for data that must persist. Saved state is discarded when the user closes the screen, swipes the app away, clears data or reboots. Use Room, DataStore or files for anything the user expects to keep, like a cart or a draft.
  • Putting a type the Bundle cannot hold. Setting a plain data class that is neither Parcelable nor Serializable throws an IllegalArgumentException. Save its id or make a small @Parcelize class.
  • Manually syncing a MutableStateFlow and SavedStateHandle. It creates two sources of truth that drift apart. Use getStateFlow and write through the handle.
  • Testing only with rotation. Rotation keeps the ViewModel, so it never exercises restoration. Test with adb shell am kill while the app is in the background.
  • Assuming process death is the same as a configuration change. Configuration changes keep the ViewModel instance alive; process death creates a new one. Your code must handle both.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between a configuration change and process death?”

“How do you prevent TransactionTooLargeException when using SavedStateHandle?”

“How would you test that your ViewModel correctly handles process death?”

“Why should we use getStateFlow instead of just updating a MutableStateFlow?”

Quiz

Which of these is the best candidate for SavedStateHandle?

What happens to a plain MutableStateFlow property in a ViewModel when the system kills the process in the background?

What exception is most commonly thrown when too much is put into SavedStateHandle?

A user fills in half a form, then swipes the app away in Recents and opens it again. What does the form's ViewModel find in its SavedStateHandle?

0 of 4 answered

Mini task

Task: Implement a Persistent Counter

Goal: Create a ViewModel whose count survives process death using SavedStateHandle.

  1. Create a CounterViewModel that takes SavedStateHandle in its constructor.
  2. Define a constant key "COUNT_KEY".
  3. Use savedStateHandle.getStateFlow("COUNT_KEY", 0) to create a StateFlow<Int> called count.
  4. Implement a function incrementCount() that sets savedStateHandle["COUNT_KEY"] = count.value + 1.
  5. Verification:
    • Write a unit test where you: a. Create SavedStateHandle(mapOf("COUNT_KEY" to 5)). b. Pass it to your CounterViewModel. c. Assert that count.value is 5. d. Call incrementCount() and assert that count.value is 6.
    • On a device, increment to 3, press Home, run adb shell am kill <your.package>, and reopen the app from Recents. The count should still be 3.
    • Now swipe the app away in Recents and open it again. The count starts from 0.

Done Condition: A passing unit test that proves the ViewModel restores a value from the handle, and a manual check that shows the count surviving process death but not the user closing the app.

Next: One-off events done right