https://blog.csdn.net/yangxjs...
哪位大佬能解释一下,以下代码的思路为什么和上面链接中的思路对不上,这段代码怎样理解?filter到底是怎样过滤质数的?
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {//sampleStart
var cur = numbersFrom(2)
for (i in 1..10) {
val prime = cur.receive()
println(prime)
cur = filter(cur, prime)
}
coroutineContext.cancelChildren() // 取消所有的子协程, 让 main 函数结束//sampleEnd
}
fun CoroutineScope.numbersFrom(start: Int) = produce<Int> {
var x = start
while (true)
send(x++) // 从 start 开始递增的无限整数流
}
fun CoroutineScope.filter(numbers: ReceiveChannel<Int>, prime: Int) = produce<Int> {
for (x in numbers)
if (x % prime != 0)
send(x)
}