如何在Kotlin中轮询通道中的项目

huangapple go评论57阅读模式
英文:

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()

输出

如何在Kotlin中轮询通道中的项目

其他项目去哪了?

英文:

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

如何在Kotlin中轮询通道中的项目

where other items gone?

答案1

得分: 1

这是因为你在两个地方获取通道的元素:forreceive()。一般来说,它们的工作方式是相同的。根据你的日志,for 接收了元素 14,而 receive() 方法得到了 23

你可以移除 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

huangapple
  • 本文由 发表于 2023年2月9日 00:40:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定