英文:
How to poll item in Channel Kotlin
问题
我在Channel
Buffer上迈出了初步的步伐。我正在学习通过Channel
轮询 项目。当我发送项目时,它并没有receive()
所有项目。我不明白为什么?
class QueueViewModel(private val application: Application) : AndroidViewModel(application) {
val basketChannel = Channel<String>(Channel.UNLIMITED)
init {
startPolling()
}
fun addItems() {
addItemInChannel(100L, "Item 1")
addItemInChannel(1000L, "Item 2")
addItemInChannel(400L, "Item 3")
addItemInChannel(500L, "Item 4")
}
fun addItemInChannel(delay: Long, item: String) {
viewModelScope.launch {
delay(delay)
logE("basketChannelItem added -> $item")
basketChannel.send(item)
}
}
fun startPolling() {
viewModelScope.launch {
Log.e(TAG, "Starting Polling")
for (element in basketChannel) {
logE("basketChannel Item poll -> $element")
basketChannel.receive()
}
}
}
}
我在活动中调用了addItems()
。
输出
其他项目去哪了?
英文:
I am doing baby step on Channel
Buffer. I am learning to Poll item through Channel
. When I send item, it doesn't receive()
all item. I don't understand why?
class QueueViewModel(private val application: Application) : AndroidViewModel(application) {
val basketChannel = Channel<String>(Channel.UNLIMITED)
init {
startPolling()
}
fun addItems() {
addItemInChannel(100L, "Item 1")
addItemInChannel(1000L, "Item 2")
addItemInChannel(400L, "Item 3")
addItemInChannel(500L, "Item 4")
}
fun addItemInChannel(delay: Long, item: String) {
viewModelScope.launch {
delay(delay)
logE("basketChannelItem added -> $item")
basketChannel.send(item)
}
}
fun startPolling() {
viewModelScope.launch {
Log.e(TAG, "Starting Polling")
for (element in basketChannel) {
logE("basketChannel Item poll -> $element")
basketChannel.receive()
}
}
}
}
I called addItems()
in activity..
Output
where other items gone?
答案1
得分: 1
这是因为你在两个地方获取通道的元素:for
和 receive()
。一般来说,它们的工作方式是相同的。根据你的日志,for
接收了元素 1
和 4
,而 receive()
方法得到了 2
和 3
。
你可以移除 basketChannel.receive()
这一行,这样你就能在 for
循环中接收所有的元素。
英文:
It's because you get items of your channel in two places: for
and receive()
. In general, they work in the same way. According to your log, for
received items 1
and 4
, while receive()
method got 2
and 3
.
You can remove basketChannel.receive()
line, and you will receive all elements in for
loop
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论