Pick the fix
Saving a draft must finish even if the user closes the screen mid-save. The save takes under a second. What should replace GlobalScope?
fun onLeave(draft: String) {
GlobalScope.launch {
saveToDisk(draft)
}
}Hint 1 of 1
Which scope lives longer than any one screen?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A An injected application-scoped CoroutineScope with a SupervisorJob
Correct. It outlives the screen, is cancellable and testable, and fits short work.
Why not the others?
- B viewModelScope. That is cancelled when the screen finishes, which is exactly when the save is needed.
- C
runBlockingin onDestroy. That blocks the main thread and can cause an ANR. - D A new
Thread { }. It is just as unowned as GlobalScope and loses coroutine cancellation.