Menu

Android Kotlin coroutines: scopes, dispatchers, cancellation
📰

Android Kotlin coroutines: scopes, dispatchers, cancellation

DEV Community: android·duong vu·3 days ago
#ay2KNLm2
#devtoandroid#devto#dev#cancelled#scope
Long article (2424 words) — no AI summary yet.
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.