Kotlin Coroutine Dispatchers and Scopes

Kotlin course · Coroutines · Lesson 48 of 51

Updated:

In the previous lesson you started coroutines with launch and async. Two questions remain: which thread does a coroutine run on, and who controls its lifetime? Dispatchers answer the first, scopes the second.

Dispatchers: where code runs

DispatcherRuns onUse for
Dispatchers.Mainthe Android UI threadupdating the UI, small quick work
Dispatchers.IOa shared pool for waiting worknetwork, database, files
Dispatchers.Defaulta pool sized to the CPU coresheavy calculations: sorting, parsing, image processing
Dispatchers.Unconfinedwherever it’s resumedrarely needed

Dispatchers.Main exists only on platforms with a UI thread, such as Android.

withContext: switch threads for one block

The usual pattern is: stay on the main thread, and switch to a background dispatcher only for the slow part. withContext runs a block on another dispatcher and returns its result:

import kotlinx.coroutines.*

suspend fun readReport(): String = withContext(Dispatchers.IO) {
    delay(200)                         // pretend to read a file
    "Report from ${if (Thread.currentThread().name.contains("worker")) "a background thread" else "main"}"
}

suspend fun countWords(text: String): Int = withContext(Dispatchers.Default) {
    text.split(" ").size               // CPU work
}

fun main() = runBlocking {
    val report = readReport()
    println(report)
    println("Words: ${countWords(report)}")
    println("Back on: ${Thread.currentThread().name}")
}

Output:

Report from a background thread
Words: 5
Back on: main

A good rule: a suspend function should be safe to call from the main thread. If it does slow work, it switches with withContext itself, so callers never have to think about threads. This is called being main-safe.

In an Android app

class ArticlesViewModel(private val repo: ArticleRepository) : ViewModel() {
    val state = MutableStateFlow<List<Article>>(emptyList())

    fun refresh() {
        viewModelScope.launch {                  // starts on Dispatchers.Main
            val articles = repo.loadArticles()   // repo switches to IO inside
            state.value = articles               // back on Main, safe to update UI
        }
    }
}

class ArticleRepository(private val api: Api) {
    suspend fun loadArticles() = withContext(Dispatchers.IO) { api.fetchArticles() }
}

Room and Retrofit’s suspend functions are already main-safe, so you don’t need withContext around them.

Scopes: who owns the coroutine

Every coroutine runs inside a CoroutineScope. When the scope is cancelled, all of its coroutines are cancelled too.

ScopeCancelled whenWhere
viewModelScopethe ViewModel is clearedViewModels
lifecycleScopethe Activity/Fragment is destroyedActivities, Fragments
rememberCoroutineScope()the composable leaves the screenJetpack Compose
coroutineScope { }its block finishesinside suspend functions
CoroutineScope(…) you createyou call cancel()your own classes
import kotlinx.coroutines.*

class Downloader {
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)

    fun start(name: String) = scope.launch {
        repeat(5) { i -> println("$name: ${(i + 1) * 20}%"); delay(100) }
    }

    fun shutdown() = scope.cancel()
}

fun main() = runBlocking {
    val d = Downloader()
    d.start("update.zip")
    delay(250)
    d.shutdown()
    delay(200)
    println("Downloader shut down")
}

Output:

update.zip: 20%
update.zip: 40%
update.zip: 60%
Downloader shut down

If you create your own scope, always cancel it when its owner goes away, or the coroutines keep running.

Job and SupervisorJob: what happens on failure

In a normal scope, one failing child cancels its siblings and the parent. That’s usually right: if one part of a task fails, the whole task has failed. With a SupervisorJob (or supervisorScope), children fail independently:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, e -> println("Logged: ${e.message}") }
    supervisorScope {
        val a = launch(handler) {
            delay(100)
            throw IllegalStateException("Image failed")
        }
        val b = launch {
            delay(200)
            println("Text loaded")    // still runs
        }
        joinAll(a, b)
    }
    println("Screen ready")
}

Output:

Logged: Image failed
Text loaded
Screen ready

The CoroutineExceptionHandler here only logs the error. viewModelScope and lifecycleScope use a SupervisorJob too, so one failing request doesn’t cancel the others.

Handling errors

Wrap the code that can fail in try/catch, inside the coroutine:

import kotlinx.coroutines.*

suspend fun loadPrice(): Int {
    delay(100)
    throw java.io.IOException("No internet")
}

fun main() {
    runBlocking {
        launch {
            val message = try {
                "Price: ₹${loadPrice()}"
            } catch (e: java.io.IOException) {
                "Couldn't load price: ${e.message}"
            }
            println(message)
        }
    }
}

Output:

Couldn't load price: No internet

For async, the exception is thrown when you call await(), so put the try around await(). A CoroutineExceptionHandler can log uncaught errors from launch, but it can’t recover from them.

Common mistakes

  • Doing network or disk work on Dispatchers.Main: the app freezes, or Android throws NetworkOnMainThreadException. Use withContext(Dispatchers.IO).
  • Using Dispatchers.IO for heavy calculations: use Default for CPU work.
  • Creating a scope and never cancelling it: the coroutines leak. Prefer the built-in lifecycle scopes.
  • Swallowing CancellationException: if you catch Exception, rethrow CancellationException, or catch only the specific exceptions you expect.

Exercise

Load a user and their settings on the IO dispatcher at the same time, process the result on Default, and print a summary.

import kotlinx.coroutines.*

suspend fun loadUser() = withContext(Dispatchers.IO) { delay(200); "Asha" }
suspend fun loadSettings() = withContext(Dispatchers.IO) { delay(150); mapOf("theme" to "dark", "lang" to "hi") }

fun main() = runBlocking {
    val (user, settings) = coroutineScope {
        val u = async { loadUser() }
        val s = async { loadSettings() }
        u.await() to s.await()
    }
    val summary = withContext(Dispatchers.Default) {
        settings.entries.joinToString { "${it.key}=${it.value}" }
    }
    println("$user: $summary")
}

Output:

Asha: theme=dark, lang=hi

FAQ

What is the difference between Dispatchers.IO and Dispatchers.Default?

IO is for waiting work like network and disk access, and can use many threads. Default is for CPU-heavy work and uses about one thread per core.

What does withContext do in Kotlin?

It runs a block of code on another dispatcher and returns the result, then continues on the original one.

What is viewModelScope?

A coroutine scope that belongs to a ViewModel. Coroutines started in it run on the main thread by default and are cancelled automatically when the ViewModel is cleared.

WhatsApp us📞 Call now