Predict the output
The request takes 3 seconds. The user rotates after 1 second. What happens to the request?
class ProfileViewModel(private val repo: UserRepository) : ViewModel() {
val user = MutableStateFlow<User?>(null)
init {
viewModelScope.launch {
user.value = repo.user("42") // takes about 3 s
}
}
}Hint 1 of 2
Is the ViewModel recreated on rotation?
Hint 2 of 2
When does viewModelScope get cancelled?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A It keeps running and the recreated screen shows the user
Correct. The ViewModel outlives the configuration change, so its scope is not cancelled.
Why not the others?
- B It is cancelled, and a new request starts when the Activity is recreated. That is what happens with lifecycleScope, which is tied to one Activity instance.
- C It finishes, but the result is lost because the old Activity is gone. The result lands in the ViewModel's StateFlow; the new Activity collects it.
- D The app crashes because the Activity it belongs to was destroyed. The coroutine holds no reference to the Activity, so nothing leaks or crashes.
Illustrative, based on Compose and Android rules; not a device recording
Text version
Rotate
- A
onPause - A
onStop - A
onDestroy - A'
onCreate - A'
onStart - A'
onResume
Press Back
- A
onPause - A
onStop - A
onDestroy - A
ViewModel. on Cleared
| State | Rotate | Press Back |
|---|---|---|
| local var | ✕ lost | ✕ lost |
| remember | ✕ lost | ✕ lost |
| remember | ✓ kept | ✕ lost |
| ViewModel | ✓ kept | ✕ lost |
| Saved | ✓ kept | ✕ lost |
| Room / disk | ✓ kept | ✓ kept |