Originally published at Shipped Code .
Most Android code launches coroutines the same way every time: viewModelScope.launch , then withContext(Dispatchers.IO) somewhere inside. That works until a download keeps going after the user leaves the screen, or a save gets cut off halfway.
Choose the scope whose lifetime matches the work, and call withContext(Dispatchers.IO) inside the function that blocks, not at the call site. Cancellation in Kotlin coroutines is cooperative, so code must reach a suspend call or ensureActive() to notice it. On Android it most often breaks when runCatching swallows CancellationException .
Work Scope Why
Load data for a screen viewModelScope Survives rotation, cancelled when the screen is gone for good
Collect a flow in an Activity or Fragment lifecycleScope + repeatOnLifecycle(STARTED) Stops collecting in the background, restarts on return
Finish a short write after the screen closes An injected application CoroutineScope Lives as long as the process
Work that must survive…