Search⌘ K
AI Features

Dispatchers

Explore the role of dispatchers in Kotlin coroutines to control which threads execute coroutines. Understand the use of Dispatchers.Default for CPU tasks, Dispatchers.Main for UI operations on Android, and Dispatchers.IO for blocking or I/O actions. Learn how to optimize thread usage and prevent blocking issues.

A necessary functionality offered by the Kotlin coroutines library lets us decide which thread (or pool of threads) a coroutine should be running (starting and resuming). We’ll do this using a dispatcher.

The English dictionary defines a dispatcher as “a person responsible for sending people or vehicles to where they are needed, especially emergency vehicles.” In Kotlin coroutines, CoroutineContext determines which thread a certain coroutine will run.

Note: Dispatchers in Kotlin Coroutines are a similar concept to RxJava Schedulers.

Default dispatcher

If we don’t set any dispatcher, the one chosen by default is Dispatchers.Default, which is designed to run CPU-intensive operations. It has a pool of threads with a size equal to the number of cores on the machine our code is running on (but not less ...