谁能解释一下它们之间的区别?我认为范围提供了一个引用(例如Job)来取消它们,而context提供了对底层线程的引用。是这样吗?
CoroutineScope
有一个CoroutineContext
。
例如,如果你有:
runBlocking { // defines coroutineScope
launch(Dispatchers.Default) { //inherits coroutineScope but changes context
}
}
runBlocking
定义了一个CoroutineScope
(了解它here)launch
继承。通过在此处明确指定调度程序来覆盖上下文。如果你看一下launch
的定义,你可以看到它需要一个可选的CoroutineContext
:
public fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
...
)
上下文的另一部分是协程的名称:
launch(CoroutineName("launchMe") + Dispatchers.Default) {
println("")
}