主要功能:
fun main() = runBlocking {
val channel = Channel<Int>()
foo(channel)
for (y in channel) println(y)
println("Done!")
}
这是可行的:
fun CoroutineScope.foo(channel: Channel<Int>) {
launch {
for (x in 1..5) channel.send(x * x)
channel.close()
}
}
这不起作用(它在通道上阻止发送):
suspend fun foo(channel: Channel<Int>) = coroutineScope {
launch {
for (x in 1..5) channel.send(x * x)
channel.close()
}
}
为什么?