通道中出现 CoroutineContext 错误

CoroutineContext error appearing in channels

首先,大家好,我是新来的。今天我只是在玩 Kotlin CoroutinesChannels。从官方文档中,我看到了这样一个频道代码片段:

val channel = Channel<Int>()
launch {
    // this might be heavy CPU-consuming computation or async logic, we'll just send five squares
    for (x in 1..5) channel.send(x * x)
}
// here we print five received integers:
repeat(5) { println(channel.receive()) }
println("Done!")

然后我决定 运行 Kotlin Playground 中的这个片段进行一些修改,这样我就可以知道有多少 coroutines 正在工作。

我的代码:

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*

fun log(msg1:String ,msg2: Int) = println("[${Thread.currentThread().name}] $msg1 $msg2")

fun main() = runBlocking {
    val channel = Channel<Int>();
    
             launch {
               for (x in 1..5) {
                channel.send(x * x) 
                log("sending",x*x)
               }
             }
    
        repeat(5){log("receiving",channel.receive())}
   
    println("Done!")
}

正如预期的那样,我收到了输出:

[main @coroutine#2] sending 1
[main @coroutine#1] receiving 1
[main @coroutine#1] receiving 4
[main @coroutine#2] sending 4
[main @coroutine#2] sending 9
[main @coroutine#1] receiving 9
[main @coroutine#1] receiving 16
[main @coroutine#2] sending 16
[main @coroutine#2] sending 25
[main @coroutine#1] receiving 25
Done!

但后来我尝试启动一个单独的 CoroutineScope,因为我在 YouTube 上观看了 Kotlin 会议,其中 'Roman Elizarov' 说明我们可以在不同 CoroutineScopes 的通道之间传输数据。所以,我尝试了这个:

import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*

fun log(msg1:String ,msg2: Int) = println("[${Thread.currentThread().name}] $msg1 $msg2")

fun main() = runBlocking {
    val channel = Channel<Int>();
    
             launch {
               for (x in 1..5) {
                channel.send(x * x) 
                log("sending",x*x)
               }
             }
    
   
    CoroutineScope{
        launch{log("receiving",channel.receive())}
    }
   
    println("Done!")
}

在 运行 之后,我得到一个错误 Type mismatch: inferred type is () -> Job but CoroutineContext was expected

这是我试图纠正此错误的方法:我添加了 Dispatchers.Default

CoroutineScope{
        launch(Dispatchers.Default){log("receiving",channel.receive())}
    }
   

抛出同样的错误。为天真的代码道歉。

有人可以帮忙吗?

我认为您混淆了 CoroutineScope class with coroutineScope 扩展函数。您正在尝试使用 {launch{...}} 块作为参数调用 CoroutineScope 构造函数,但构造函数需要一个 CoroutineContext。

CoroutineScope 更改为 coroutineScope 并为 kotlinx.coroutines.coroutineScope 添加导入。