首先,大家好,我是新来的。今天我只是和KotlinCoroutines
和Channels
。从官方文档中,我看到了如下通道的一个代码段:
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!")
然后,我决定对snippetKotlin 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”说明了我们可以在不同CoroutineScope的通道之间传输数据。所以,我尝试了这个:
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类与coroutineScope扩展功能混淆。您正在尝试使用该{launch{...}}
块作为参数调用CoroutineScope构造函数,但是该构造函数希望使用CoroutineContext。
更改CoroutineScope
为coroutineScope
并添加的导入kotlinx.coroutines.coroutineScope
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句