有办法具有生产者成员功能吗?

时间:2019-08-22 02:11:09

标签: kotlin kotlin-coroutines

使用协程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(...)

1 个答案:

答案 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++
            }
        }
    }
}