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

mboudraa

12/06/2018, 2:59 PM
Hi guys, i’m writing a
startWith
extension on
ReceiveChannel
and i was wondering which is the best way to do that. I have currently 2 implementations:
Copy code
suspend fun <A> ReceiveChannel<A>.startWith(element: A): ReceiveChannel<A> {
    val channel = Channel<A>()
    channel.offer(element)
    consumeEach { channel.send(it) }
    return channel
}
Copy code
suspend fun <A> ReceiveChannel<A>.startWith(element: A, coroutineScope: CoroutineScope): ReceiveChannel<A> {
    return coroutineScope.produce {
        offer(element)
        this@startWith.consumeEach { this@produce.send(it) }
    }
}
I’m not sure what’s the difference is between the 2 and which is the best approach
s

streetsofboston

12/06/2018, 3:07 PM
I would prefer the first one, even if it is just for the simple reason it doesn’t need an additional
CoroutineScope
parameter. Sidenote: You call
offer
, but that could fail. Wouldn’t that mean the returning channel won’t start with
element
?
m

mboudraa

12/06/2018, 3:09 PM
it fails only if the channel don’t have the room to send the offered element. since it’s the first one. should never happen
s

streetsofboston

12/06/2018, 3:10 PM
Yes, you’re right. The
channel
is brand ‘new’ 🙂
m

marstran

12/06/2018, 3:53 PM
I think you should make sure that the output channel has the same capacity as the input channel.
m

mboudraa

12/06/2018, 4:02 PM
looks like the 1st implementation doesnt work anyway
So the solution is either the second using
send
or using
GlobalScope
to avoid forwarding the
CoroutineScope
everytime
d

dave08

12/07/2018, 3:42 AM
1st probably doesn't work because it's a rendez-vous channel, if it has at least capacity 1, it should be fine.
3 Views