Kotlin:Coroutines范围与Coroutine背景

问题描述 投票:4回答:3

谁能解释一下它们之间的区别?我认为范围提供了一个引用(例如Job)来取消它们,而context提供了对底层线程的引用。是这样吗?

kotlin kotlin-coroutines
3个回答
1
投票

CoroutineScope有一个CoroutineContext

例如,如果你有:

runBlocking { // defines coroutineScope

    launch(Dispatchers.Default) { //inherits coroutineScope but changes context

    }
}

runBlocking定义了一个CoroutineScope(了解它herelaunch继承。通过在此处明确指定调度程序来覆盖上下文。如果你看一下launch的定义,你可以看到它需要一个可选的CoroutineContext

public fun CoroutineScope.launch(
    context: CoroutineContext = EmptyCoroutineContext,
    ...
)

上下文的另一部分是协程的名称:

launch(CoroutineName("launchMe") + Dispatchers.Default) {
    println("")
}
© www.soinside.com 2019 - 2024. All rights reserved.