Predict the output
A user fills in step 2 of a sign-up flow, switches apps, and Android kills the process. They return from Recents. What do they see?
class SignUpViewModel(private val handle: SavedStateHandle) : ViewModel() {
var email: String = "" // set on step 1
val step = handle.getStateFlow("step", 1)
fun next() { handle["step"] = step.value + 1 }
}Hint 1 of 1
Which values were written to SavedStateHandle?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Step 2, but the email from step 1 is empty
Correct. The step is in SavedStateHandle and is restored; the plain field is lost with the process.
Why not the others?
- B Step 1 with everything empty. The step number was saved, so the flow is restored at step 2.
- C Step 2 with the email intact. A plain ViewModel field doesn't survive process death.
- D The launcher screen, because the task was removed. Recents restores the task and its saved state.
Illustrative, based on Compose and Android rules; not a device recording
Text version
Home, then back
- A
onPause - A
onStop - A
onSave Instance State - A
onRestart - A
onStart - A
onResume
Home, killed, back
- A
onPause - A
onStop - A
onSave Instance State - (process killed: no more callbacks)
- A'
onCreate (with saved Bundle) - A'
onStart - A'
onResume
| State | Home, then back | Home, killed, back |
|---|---|---|
| local var | ✓ kept | ✕ lost |
| remember | ✓ kept | ✕ lost |
| remember | ✓ kept | ✓ kept |
| ViewModel | ✓ kept | ✕ lost |
| Saved | ✓ kept | ✓ kept |
| Room / disk | ✓ kept | ✓ kept |