I'm looking for a way to subscribe to a conflated ...
# coroutines
d
I'm looking for a way to subscribe to a conflated
BroadcastChannel
but ignore any items that may already be in that channel at the time of subscription. Is this possible? (example in thread)
Copy code
val demoScope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)

val myBroadcastChannel = BroadcastChannel<String>(Channel.CONFLATED)

myBroadcastChannel.send("1")

demoScope.launch {
    myBroadcastChannel.openSubscription().consumeEach {
        println("subscriber1: $it")
    }
}

delay(1000)
myBroadcastChannel.send("2")
delay(1000)
myBroadcastChannel.send("3")
delay(1000)
myBroadcastChannel.send("4")


demoScope.launch {
    myBroadcastChannel.openSubscription().consumeEach {
        println("subscriber2: $it")
    }
}

delay(1000)
myBroadcastChannel.send("5")

/* current output 
    subscriber1: 1
    subscriber1: 2
    subscriber1: 3
    subscriber1: 4
    subscriber2: 4
    subscriber2: 5
    subscriber1: 5
 */

/* deesired output 
    subscriber1: 2
    subscriber1: 3
    subscriber1: 4
    subscriber2: 5
    subscriber1: 5
 */
o
I think your best bet is going to be checking
valueOrNull
, and if it is non-null, drop the first element from the subscription
d
Good suggestion. I'm still trying to see if there are any edge cases, but it looks like I can get away with providing the channel like:
Copy code
myBroadcastChannel.openSubscription().apply {
        receiveOrNull()
}
in order to get a receive channel
Thanks!
I'll have to check it out later, but I have some tests that appear to be getting hung on
receiveOrNull()
that's preventing further execution.
o
are you expecting
receiveOrNull()
to return if the channel is empty?
d
I was, but see that isn't what it's supposed to do. I can see why it's getting hung up now
d
There it is,
poll
looks like it works. Still waiting on some tests, but the problematic ones have passed
Thanks again