Kotlin 有没有一种方法可以拥有生产者成员函数?
使用coroutines 1.3-RC2,我希望执行以下操作:Kotlin 有没有一种方法可以拥有生产者成员函数?,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,使用coroutines 1.3-RC2,我希望执行以下操作: class Foo { fun getPrimes() = produce { var i = 0 while (true) { if (i.isPrime()) { send(i) } i++ } } } 但它抱怨说,由于接收器不匹配,product无法使用。我
class Foo {
fun getPrimes() = produce {
var i = 0
while (true) {
if (i.isPrime()) {
send(i)
}
i++
}
}
}
但它抱怨说,由于接收器不匹配,product
无法使用。我可以将生成{}
包装在runBlocking
中,它可以编译,但它会阻塞
因此,如何实现这种生产者模式,使客户端代码可以运行
myFoo.getPrimes()。consumeEach(…)
?product
需要一个协同程序作用域来运行。您可以传递一个作用域:
class Foo {
fun getPrimes(scope: CoroutineScope) = scope.produce {
var i = 0
while (true) {
if (i.isPrime()) {
send(i)
}
i++
}
}
}
或者,例如,标记getPrimes
suspend并创建一个新范围:
class Foo {
suspend fun getPrimes() = coroutineScope {
produce {
var i = 0
while (true) {
if (i.isPrime()) {
send(i)
}
i++
}
}
}
}
谢谢你的解决方案!尽管我仍然在这方面遇到问题,就像我在
runBlocking{
中遇到的问题一样,调用代码从未从getPrimes
中获取返回值。这意味着如何调用它有一些细微差别吗?啊,我让它工作了。从coroutineScope{product{/code>更改为GlobalScope.product{
具有所需的行为。尽管如果有人能提供一个很好的解释,下一个用户可能会受益:)