https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Dan Lowe

11/24/2019, 8:01 AM
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

octylFractal

11/24/2019, 8:04 AM
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

Dan Lowe

11/24/2019, 8:18 AM
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

octylFractal

11/24/2019, 8:37 AM
are you expecting
receiveOrNull()
to return if the channel is empty?
d

Dan Lowe

11/24/2019, 8:39 AM
I was, but see that isn't what it's supposed to do. I can see why it's getting hung up now
d

Dan Lowe

11/24/2019, 8:44 AM
There it is,
poll
looks like it works. Still waiting on some tests, but the problematic ones have passed
Thanks again
3 Views