Dispatchers
In the section discussing the high cost of threads, we touched on the concept of executors in Java. Previously, we utilized a coroutine scope for writing asynchronous code. Now, we will examine the rationale behind the use of coroutine dispatchers in Kotlin.
When we ran our coroutines using the runBlocking
function, their code was executed on the main thread.
You can check this by running the following code:
fun main() {
runBlocking {
launch {
println(Thread.currentThread().name)
}
}
}
This prints the following output:
> main
In contrast, when we run a coroutine using GlobalScope
, it runs on something called DefaultDispatcher
:
fun main() {
runBlocking {
GlobalScope.launch {
println("GlobalScope.launch: ${Thread.currentThread().name}")
}
}
}
This prints the following output:
> DefaultDispatcher-worker-1
DefaultDispatcher
is a thread pool that...