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

Antanas A.

05/24/2019, 12:45 PM
I hope someday channels will be bound to coroutine lifecycles and we no longer need explicitly do coroutineContext[Job]!!.invokeOnCompletion { broadcastChannel.close() }
g

gildor

05/24/2019, 1:11 PM
But you already shouldn't do this
What is your use case, how do you use this btoadcast channel? Because if you use comsumeEach no need to do this Or even better to use Flow which make leak even harder
Just replace openSubscription with asFlow
a

Antanas A.

05/24/2019, 1:23 PM
the use case is that one module uses single channel from another module. And that module needs hook to that channel multiple times (in module), and also provides new single channels to other modules.
Copy code
class Module(inputStream) { 
    val broadcast = inputStream.broadcast()
   // multi usage: launch { broadcast.consumeEach { ... } }
    fun output() = broadcast.openSubscription().map(...)
}
It's all ok with a consumeEach as you said, but it's not ok with channels which is returned by output() function because they are outside of controllable scope of a module
would be nice, that broadcast() will be suspend fun and bounds to parent's coroutine context
it's one of examples, but we've noticed that we are carefully controlling coroutines lifecycles
and in parallel there is a need to control all channels "lifecycles"
it would be easier that all channel related stuff will be bound automatically to coroutine lifecycles (as channel is implicitly a coroutine also)
and there is a case that
broadcast()
will connect to
inputStream
channel and consumes from that forever
g

gildor

05/24/2019, 3:01 PM
Just use Flow
You cannot start it without suspending, so it more safe
Also it has more operators, so maybe you can write it in a more simple way
l

louiscad

05/24/2019, 6:53 PM
Using
asFlow
for a
BroadcastChannel
will not solve the issue as a
BroadcastChannel
stays hot while it's not been explicitly closed with
close()
.
g

gildor

05/25/2019, 12:46 AM
@louiscad Yes, you right, I see now The problem of this code is inputStream, not even broadcast channel actually, broadcast channel just used to close input stream, and I'm not really sure that it's correct enough
If you want to reuse scope, invokeOnCompletion is fine imo, you can even write extension function to simplify attaching of resources (or even Closables) to scope But I really don't think that it is problem of Channels
m

Matej Drobnič

05/25/2019, 6:26 AM
I think your use case should be handled by flow, but flow does not support that yet.
3 Views