我想使用 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/