Kotlin ConflatedBroadcastChannel.offer() doesn't work?

Viewed 543

I am sending a value via MyRepository.myConflatedChannel.offer(myvalue).

I then expect to receive it in collect { } or onEach { } blocks in my ViewModel. However, neither function is invoked. It is as if nothing is passed down the ConflatedBroadcastChannel.

Has anybody seen a similar problem?

1 Answers

Make sure you properly work with receiving values.

If you use the ConflatedBroadcastChannel, you can use either OpenSubscription to get a ReceiveChannel or you can represent it as flow (with asFlow).

Note that consume and consumeEach are terminal, they perform an action and then cancel the channel after the execution of the block. See this.

First case:

val receivingChannel = MyRepository.myConflatedChannel.openSubscription()
// then you can consume values using for example a for loop, e.g.:

launch {
    for (value in receivingChannel) {
        // do something
    }
}

Second case:

val receivingFlow = MyRepository.myConflatedChannel.asFlow()

launch {
    receivingFlow.collect {
        // do something
    }
}
Related