kotlin - 如何在 Kotlin Actor 中获得非阻塞无限循环?

标签 kotlin kotlin-coroutines

我想使用 Kotlin Actor 消费一些流数据
我想把我的消费者放在一个 Actor 里面,而它在一个无限循环中轮询while(true) .然后,当我决定时,我会发送一条消息来阻止消费者。
目前我有这个:

while(true) {
     for (message in channel){    <--- blocked in here, waiting
            when(message) {
                is MessageStop -> consumer.close()
                else -> {}
        }
    }

    consumer.poll()
}
问题
这样做的问题是它只在我向参与者发送消息时运行,所以我的消费者在其余时间没有轮询,因为 channel 阻塞等待接收下一条消息
有没有其他选择?,有同样问题的人?或者类似于 Actor 但没有被 Kotlin 中的 channel 阻止的东西?

最佳答案

由于 channel 只是一个 channel (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-channel/index.html),您可以先检查 channel 是否为空,如果是则开始轮询。否则处理消息。
例如。

while(true) {

    while (channel.isNotEmpty()) {
        val message = channel.receive()
        when(message) {
            is MessageStop -> consumer.close()
            else -> {}
        }
     }

    consumer.poll()
}

关于kotlin - 如何在 Kotlin Actor 中获得非阻塞无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64594812/

相关文章:

android - 无法找到明确的 Activity (Kotlin)

java - BuildConfig 是公共(public)的,应在名为 BuildConfig.java 的文件中声明

android - GlobalScope 与 CoroutineScope 与生命周期范围

kotlin - withContext 和 suspendCancellableCoroutine 之间的区别

unit-testing - 协程测试失败, "This job has not completed yet"

kotlin - Kotlin:在列表 “in parallel”上应用暂停功能?

android - 如何在单元测试中使viewModelScope等待挂起功能

android - 项目不会使用 Kotlin 1.1.3 构建

java - 表达式时删除 Kotlin 中的中断

kotlin - Gradle 扩展 : can plain Kotlin types be used instead of Property<T> for properties with simple values?