【问题标题】:Using coroutine channels and the livedata builder together一起使用协程通道和 livedata builder
【发布时间】:2019-10-23 08:58:16
【问题描述】:

如何将协程通道与 livedata 协程构建器 (androidx.lifecycle:lifecycle-livedata-ktx architecture component) 一起使用,以持续侦听从 websocket 库生成到 ReceiveChannel<String> 的消息?

我的第一个想法是这样实现

val user: LiveData<String> = liveData {
    while(true) {
        val data = myWebsocketChannel.receive() //Channel suspend function
        emit(data)
    }
}

但这感觉有点“非 kotliny”,我的直觉告诉我有更好的解决方法。 有没有更好的方法来处理从协程通道接收到的发布数据?

【问题讨论】:

    标签: android android-livedata kotlin-coroutines


    【解决方案1】:

    我会这样写:

    val user: LiveData<User> = liveData {
        myWebsocketChannel.consumeEach { data ->
           emit(data)
       }
    }
    

    myWebsocketChannel.consumeEach { ... } 将永远迭代(暂停,如果通道为空),直到有人关闭 myWebsocketChannel。在生产者端——我们正在监听套接字的地方,我们应该小心不要过早关闭通道。

    希望对你有帮助:)

    【讨论】:

    • 一旦频道中没有更多的项目排队,它会停止运行吗?
    • 如果有人在通道的“另一边”调用 c​​hannel.close(),它将停止运行。否则它将无限迭代(如果通道为空则暂停)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多