- Learning Concurrency in Kotlin
- Miguel Angel Castiblanco Torres
- 227字
- 2021-08-05 10:46:48
Using a specific dispatcher when starting the coroutine
So far, we have seen how to create coroutines using async() and launch(), but in both cases we were using the default dispatcher. Consider the following code:
fun main(args: Array<String>) = runBlocking {
val task = launch {
printCurrentThread()
}
task.join()
}
Here, printCurrentThread(), as its name suggests, will just print the name of the current thread to the standard output:
fun printCurrentThread() {
println("Running in thread [${Thread.currentThread().name}]")
}
By running this code, we see that by default the coroutine will run in DefaultDispatcher, which as the time of writing is the same dispatcher as CommonPool – but be aware that this could change in the future.
If we update main() to create a CoroutineDispatcher the same way we did before, and send it to launch(), we will see that the coroutine is being executed in the thread that we indicated, for example:
fun main(args: Array<String>) = runBlocking {
val dispatcher = newSingleThreadContext(name = "ServiceCall")
val task = launch(dispatcher) {
printCurrentThread()
}
task.join()
}
The output looks like the following screenshot. Notice that the name of the thread is the same name that we set for the dispatcher:

Now we will do likewise in MainActivity:
private val dispatcher = newSingleThreadContext(name = "ServiceCall")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
launch(dispatcher) {
// TODO Call coroutine here
}
}
- Oracle WebLogic Server 12c:First Look
- Kibana Essentials
- Visual Basic 6.0程序設計計算機組裝與維修
- Java 9 Programming Blueprints
- JavaScript+jQuery開發實戰
- 機器人Python青少年編程開發實例
- 用Flutter極速構建原生應用
- Apache Mesos Essentials
- 精通Linux(第2版)
- Android應用案例開發大全(第二版)
- 好好學Java:從零基礎到項目實戰
- UI設計全書(全彩)
- Unity 3D腳本編程:使用C#語言開發跨平臺游戲
- R語言:邁向大數據之路(加強版)
- Mastering HTML5 Forms