rog*_*one 3 kotlin kotlin-coroutines
我有一个Runner实现CoroutineScope接口的类,如下所示。它有一个名为 的挂起函数run。当我在此挂起函数中使用协同例程构建器函数(launch, )时,我收到以下警告asyncrun
由于挂起函数的 CoroutineScope 接收器而导致的 coroutineContext 不明确
该类Runner实现了一个 coroutineContext 属性。有人可以解释警告消息背后的逻辑吗?
class Runner: CoroutineScope {
override private val coroutineContext = Dispatchers.IO
suspend fun run() {
val job1 = launch { delay(2000); println("launching job1") }
val job2 = launch { delay(2000); println("launching job2") }
listOf(job1, job2).forEach { it.join() }
}
}
Run Code Online (Sandbox Code Playgroud)
由于挂起修饰符,它是不明确的。您的run()函数将从另一个协程作用域中调用。因此,launch其中的构建器可以启动协程或在现有协程中挂起。这就是歧义。您可以通过删除挂起修饰符来修复它:
class Runner : CoroutineScope {
override val coroutineContext = Dispatchers.IO
fun run() = launch {
val job1 = launch { delay(2000); println("launching job1") }
val job2 = launch { delay(2000); println("launching job2") }
listOf(job1, job2).forEach { it.join() }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1451 次 |
| 最近记录: |