Coroutine Context and Threads
We'll cover the following...
The call to the launch()
and runBlocking()
functions resulted in the coroutines executing in the same thread as the caller’s coroutine scope. That’s the default behavior of these function since they carry a coroutine context from their scope. You may, however, vary the context and the thread of execution of the coroutines where you like.
Explicitly setting a context
You may pass a CoroutineContext to the launch() and runBlocking() functions to set the execution context of the coroutines these functions start.
The value of Dispatchers.Default
for the argument of type CoroutineContext
instructs the coroutine that is started to execute in a thread from a DefaultDispatcher
pool. The number of threads in this pool is either 2 or equal to the number of cores on the system, whichever is higher. This pool is intended to run computationally intensive tasks.
The value of Dispatchers.IO
can be used to execute coroutines in a pool that is dedicated to running IO intensive tasks. That pool may grow in size if threads are blocked on IO and more tasks are created.
Dispatchers.Main
can be used on Android devices and Swing UI, for example, to run tasks that update the UI from only the main
thread.
To get a feel for how to set the context for launch()
, let’s take the previous example and make a change to one of the launch()
calls, like so:
runBlocking {
launch(Dispatchers.Default) { task1() }
launch { task2() }
println("called task1 and task2 from ${Thread.currentThread()}")
}
...