【发布时间】: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()
}
...但到目前为止,还没有雪茄。
【问题讨论】: