官术网_书友最值得收藏!

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
}
}
主站蜘蛛池模板: 威信县| 察哈| 沈丘县| 大石桥市| 洪江市| 静宁县| 曲阳县| 余姚市| 东山县| 长汀县| 淄博市| 旌德县| 达日县| 元朗区| 青川县| 宣恩县| 凭祥市| 梅州市| 绥中县| 瑞丽市| 华坪县| 舒兰市| 洛南县| 镇平县| 清徐县| 鄢陵县| 新乐市| 金寨县| 图木舒克市| 德阳市| 沿河| 双牌县| 赤壁市| 亚东县| 新竹市| 城步| 汽车| 浙江省| 洞口县| 安义县| 黑河市|