[英]How can I get a non-blocking infinite loop in a Kotlin Actor?
我想使用 Kotlin 演員消耗一些流數據
我想把我的消費者放在一個演員中,同時它在無限循環中輪詢while(true)
。 然后,當我決定時,我會發送一條消息來阻止消費者。
目前我有這個:
while(true) {
for (message in channel){ <--- blocked in here, waiting
when(message) {
is MessageStop -> consumer.close()
else -> {}
}
}
consumer.poll()
}
問題
這樣做的問題是它只在我向演員發送消息時運行,所以我的消費者不會輪詢其余時間,因為通道正在阻塞等待接收下一條消息
有沒有其他選擇?,有同樣問題的人嗎?,或者類似於演員但沒有被 Kotlin 中的頻道阻止的東西?
最后我將 AKKA 與 Kotlin 一起使用,我發現這樣更容易
您應該使用postDelayed()
,例如:
final Runnable r = new Runnable() {
public void run() {
// your code here
handler.postDelayed(this, 1000)
}
}
您可以使用所需的毫秒延遲更改1000
。 此外,我強烈建議將您的代碼放在一個線程中(如果您還沒有)以防止 ANR(應用程序無響應)
由於頻道只是一個頻道( https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-channel/index.html )您可以先檢查頻道是否為空如果是這樣開始你的投票。 否則處理消息。
例如
while(true) {
while (channel.isNotEmpty()) {
val message = channel.receive()
when(message) {
is MessageStop -> consumer.close()
else -> {}
}
}
consumer.poll()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.