使用协程1.3-RC2,我要执行以下操作:
class Foo {
fun getPrimes() = produce {
var i = 0
while (true) {
if (i.isPrime()) {
send(i)
}
i++
}
}
}
但是它抱怨produce
由于接收器不匹配而无法使用。我可以将produce{}
包装在runBlocking
中,并且可以编译,但是会阻塞。
那么,如何实现这种生产者模式,以使客户端代码可以运行myFoo.getPrimes().consumeEach(...)
?
答案 0 :(得分:1)
produce
需要一个协程作用域才能运行。您可以传递一个作用域:
class Foo {
fun getPrimes(scope: CoroutineScope) = scope.produce {
var i = 0
while (true) {
if (i.isPrime()) {
send(i)
}
i++
}
}
}
,例如,将getPrimes
标记为暂停并创建新的作用域:
class Foo {
suspend fun getPrimes() = coroutineScope {
produce {
var i = 0
while (true) {
if (i.isPrime()) {
send(i)
}
i++
}
}
}
}