Search code examples
androidkotlinkotlin-coroutinesandroid-viewmodel

How to poll item in Channel 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

enter image description here

where other items gone?


Solution

  • 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