I have a `Channel` that I'm converting to a flow ...
# coroutines
a
I have a
Channel
that I'm converting to a flow and listening to. As soon as the channel is created I'm sending through an initial default value. Right before that happens I'm observing the
flow
using the onEach pattern. The flow, however, is not receiving the initial value, presumably because there's an asynchronous launch involved. Does anyone have any idea how to get around this issue?
o
I don't think
onEach
observes the flow at all? are you eventually calling a terminal op like
launchIn
or
collect
?
☝🏼 1
a
Sorry yes I'm calling
launchIn
o
not sure then, if you can provide an example that reproduces the issue I can look a little further
a
Sure, one minute
Copy code
object Woofers {
  fun doStuff(scope: CoroutineScope) {
    val channel = BroadcastChannel<Int>(Channel.BUFFERED)
    channel
        .asFlow()
        .onEach { println("Value: $it") }
        .launchIn(scope)

    // Won't be received
    channel.offer(1)
  }
}
That repros it
o
yea, it looks like an ordering thing. I tried a few tricks, but I don't know if there's an easy way around it
if it works for you, using
flow.onStart { emit(1) }
might be a better solution
s
Is it only the first emission/value that goes missing?
What if you tried a regular Channel instead of a BroadcastChannel? I don’t see a reason why that would work, but i’m just curious 🙂
a
I ended up using`flow.onStart`which worked. It could be more than the first value - presumably its all of the values until the launch call is up. I haven't tried a regular Channel I'll see if that makes a difference