Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 有没有一种方法可以拥有生产者成员函数?_Kotlin_Kotlin Coroutines - Fatal编程技术网

Kotlin 有没有一种方法可以拥有生产者成员函数?

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无法使用。我

使用coroutines 1.3-RC2,我希望执行以下操作:

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{
具有所需的行为。尽管如果有人能提供一个很好的解释,下一个用户可能会受益:)