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

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
}
}
主站蜘蛛池模板: 仁寿县| 泰顺县| 深泽县| 治县。| 岳阳市| 德保县| 施秉县| 龙口市| 姜堰市| 长治市| 米林县| 沐川县| 东乡县| 陈巴尔虎旗| 新巴尔虎右旗| 科技| 巴青县| 平湖市| 潢川县| 会理县| 化德县| 孝感市| 安顺市| 克拉玛依市| 烟台市| 界首市| 略阳县| 津南区| 通化县| 文成县| 罗江县| 扶风县| 湟中县| 哈巴河县| 青铜峡市| 米易县| 黄石市| 高唐县| 肃北| 合水县| 靖西县|