【发布时间】:2020-11-21 13:23:07
【问题描述】:
在启动协程时,它可能只创建一个 CoroutineScope 并从中调用 launch{} -- doSomething_2(),
或从 CoroutineScope 派生类并使用要启动的类{}。 --doSomething_1()。
这两种方式有区别吗,首选哪种方式?
class AClass : CoroutineScope {
override val coroutineContext: CoroutineContext = Dispatchers.Main
var theJob1: Job? = null
var theJob2: Job? = null
fun doSomething_1() {
theJob1 = launch(Dispatchers.IO) {
// ... ...
}
}
fun doSomething_2() {
theJob2 = CoroutineScope(Dispatchers.IO).launch {
// ... ...
}
}
fun dispose() {
theJob1?.cancel()
theJob2?.cancel()
}
}
【问题讨论】:
标签: kotlin-coroutines coroutinescope