【问题标题】:Continuously receiving from a coroutine Channel within an Activity不断从 Activity 中的协程 Channel 接收
【发布时间】:2020-04-01 12:24:08
【问题描述】:

我正在编写一个在 Activity 中使用 Kotlin 协程的 Android 应用程序。我有以下通道声明,可用于接收通知流,并想了解如何最好地在主 (UI) 调度程序上执行相关操作:

    private var stateNotifications: Channel<Notification>? = null

我目前构建了一个Handler,以便可以轮询stateNotifications。它的设置如下所示:

            stateNotificationHandler.postDelayed(
                handleStateNotifications,
                100L
            )

handleStateNotifications 声明如下:

    private val handleStateNotifications: Runnable = Runnable {
        run {
            val x = when (stateNotifications?.poll()) {
                is ...
            } // FIXME: UPDATE UI
            stateNotificationHandler.postDelayed(
                handleStateNotifications,
                handleStateNotificationsInterval
            )
        }
    }

这似乎有效。但是,我认为应该有一种方法可以让stateNotifications 在默认调度程序上接收,然后将事件分配给 UI 线程。我在想这样的事情:

            launch {
                flow<Notification?> {
                    emit(notifications.receive())
                }.onEach { perhaps-invoke-a-handler-to-update-ui }.collect()
            }

...但到目前为止,还没有雪茄。

【问题讨论】:

    标签: android kotlin coroutine


    【解决方案1】:

    睡了一夜好觉后,我意识到我需要使用基于flow 的良好且响应迅速的方法不断循环接收,例如:

            job = defaultScope.launch() {
                val notifications = Channel<Handwashing.Notification>()
    
                launch {
                    flow<Notification?> {
                        while (true) {
                            emit(notifications.receive())
                        }
                    }.onEach {
                        stateNotificationHandler.postDelayed( {
                            // Do some UI thing
                        },  0)
                    }.collect()
                }
    
                // Push notifications to the notifications channel.
            }
        }
    

    请注意,使用外部 job 对于在以后需要整理时取消此处的所有协程非常重要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-22
      • 2017-03-12
      • 2023-03-23
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 2023-01-10
      • 2021-01-03
      相关资源
      最近更新 更多