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

Abhishek Bansal

02/04/2020, 10:12 AM
Does
BroadcastChannel#openSubscription.consumeAsFlow()
completes when collected? If not how do I go about cancelling subscription? I was trying to do this in my class so that client does not have to worry about cancelling the subscription
Copy code
private fun getResponseChannel(): Flow<ContentResponse> {
        val channel = responseChannel.openSubscription()
        return channel
            .consumeAsFlow()
            .onCompletion {
                Timber.d("Cancelled")
                channel.cancel()
            }
    }
But it seems that
onCompletion
never gets called
d

dekans

02/04/2020, 10:19 AM
It completes when channel is closed
a

Abhishek Bansal

02/04/2020, 10:22 AM
okay.. thanks for your reply. My use case is that I wish to achieve RxJava’s
PublishSubject
like behavior. I wish to have a broadcast channel where multiple subscribers can come and go dynamically. is this possible with this setup at all? I cannot close original channel I just wish to close new subscription when its done.
s

streetsofboston

02/04/2020, 12:48 PM
Yup, this is possible and your code snippet looks good. IIRC, onCompletion is called only when the upstream Flow (which basically is the broadcast channel) completes (error or plain closes). You canceling the CoroutineScope in which you call
collect
on the
Flow
returned by
getResponseChannel
('un-subscribing' in Rx terms), won't cause a call to onCompletion.
👍 1
3 Views