【问题标题】:Is there a way to have a producer member function?有没有办法拥有生产者成员功能?
【发布时间】:2019-08-22 02:11:09
【问题描述】:

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

【问题讨论】:

    标签: kotlin kotlin-coroutines


    【解决方案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++
                }
            }
        }
    }
    

    【讨论】:

    • 感谢您的解决方案!虽然我仍然遇到与runBlocking { 一样的问题,其中调用代码永远不会从getPrimes 获得返回值。这有什么细微的差别吗?
    • 啊,我让它工作了。从 coroutineScope { produce { 更改为 GlobalScope.produce { 具有所需的行为。虽然如果有人能提供一个很好的解释,下一个看这个的用户可能会受益:)
    猜你喜欢
    • 2015-02-12
    • 2021-12-10
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多