Hi guys, i’m writing a `startWith` extension on `R...
# coroutines
m
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
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
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
Yes, you’re right. The
channel
is brand ‘new’ 🙂
m
I think you should make sure that the output channel has the same capacity as the input channel.
m
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
1st probably doesn't work because it's a rendez-vous channel, if it has at least capacity 1, it should be fine.