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

julioyg

01/30/2019, 4:27 PM
👋 is it ok if I open a subscription to a broadcastChannel and consume the items inside a coroutine and when I'm not interested on receiving items from the channel I just cancel the coroutine or do i need to explicitly close the channel?
will that leave the channel open and will leak memory?
g

gildor

01/30/2019, 4:40 PM
Cancel coroutine is enough
j

julioyg

01/30/2019, 4:40 PM
but after closing the coroutine if I check
isClosedForReceive
it's
false
...
Copy code
fun main() {
    var channel: ReceiveChannel<String>? = null

    var broadcastChannel = BroadcastChannel<String>(1)

    val job = GlobalScope.launch {
        channel = broadcastChannel.openSubscription()
    }

    job.cancel()

    Thread.sleep(1000)

    println("is closed ${channel!!.isClosedForReceive}")
}
that prints
false
is that ok?
(sorry, just to make sure we are both talking about the same thing)
a

Allan Wang

01/30/2019, 6:45 PM
I actually have this by design, as I use BroadcastChannel as a replacement for RxJava's subjects. I intentionally keep it open even outside the lifecycle, in cases other components offer values beyond the lifecycle. This avoids the crashes, and so long as you aren't dealing with UI related models, I think it should be fine
j

julioyg

01/30/2019, 7:21 PM
my bad, it gets closed if I call
consumeEach
thanks bot for the help
@Allan Wang you don't need to keep the channel open, because it's a
BroadcastChannel
so when you call
openSubscription
it creates a new channel, so (reading the github issue) even if you close the channel returned by
openSubscription
you can still send items to the
BroadcastChannel
2 Views