https://kotlinlang.org logo
Title
a

alexsullivan114

04/02/2020, 7:20 PM
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

octylFractal

04/02/2020, 7:22 PM
I don't think
onEach
observes the flow at all? are you eventually calling a terminal op like
launchIn
or
collect
?
☝️🏼 1
a

alexsullivan114

04/02/2020, 7:22 PM
Sorry yes I'm calling
launchIn
o

octylFractal

04/02/2020, 7:23 PM
not sure then, if you can provide an example that reproduces the issue I can look a little further
a

alexsullivan114

04/02/2020, 7:23 PM
Sure, one minute
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

octylFractal

04/02/2020, 7:38 PM
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

streetsofboston

04/02/2020, 9:56 PM
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

alexsullivan114

04/04/2020, 3:34 PM
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