What are dispatchers in Kotlin coroutines?
What are dispatchers?
A dispatcher is an essential functionality provided by Kotlin coroutines. It helps us to conclude which coroutine will run on which thread from a pool of threads.
Types of dispatchers
There are four types of dispatchers depending on the work we want the coroutine to do.
- Default dispatcher
- Main dispatcher
- IO dispatcher
- Unconfined dispatcher
Default dispatcher
We use the default dispatcher when we want to run CPU-intensive functions. If we forget to choose our dispatcher, this dispatcher will be selected by default.
Syntax
launch(Dispatchers.Default)
Main dispatcher
It is not used very often. It’s only used in Android applications when we want to interact with the UI. It is restricted to the main thread as it is only used when we want to run our coroutine on the main thread. If we’re going to use this, we first need to set a dispatcher using Dispatchers.setMain(dispatcher).
Syntax
launch(Dispatchers.Main)
IO dispatcher
It is used when we want to block threads with I/O (input-output) operations, such as when we want to read/write files.
Syntax
launch(Dispatchers.IO)
Unconfined dispatcher
An unconfined dispatcher isn’t restricted to a particular thread. This dispatcher contrasts with those mentioned earlier as it changes no threads. At the point when it is begun, it runs on the thread on which it was begun.
Syntax
launch(Dispatchers.Unconfined)
Example
suspend fun main(): Unit = coroutineScope{
launch(Dispatchers.Default) {
println("Default : Thread ${Thread.currentThread().name}")
}
launch(Dispatchers.Unconfined) {
println("Unconfined : Thread ${Thread.currentThread().name}")
}
launch(Dispatchers.IO) {
println("IO : Thread ${Thread.currentThread().name}")
}
}Explanation
- Line 1: Wrap a suspending main body using
coroutineScope. - Line 3: Start a coroutine on
Dispatcher.Default. - Line 4: Start a coroutine on
Dispatcher.Unconfined. - Line 5: Start a coroutine on
Dispatcher.IO.
Free Resources