How can you emit (infinite) values before the real...
# coroutines
h
How can you emit (infinite) values before the real flow emits? I want to combine two flows: flow b into flow a. Flow a should not wait until the first emission of flow b, but should emit
null
until b emits values. After b emits some values, the last value of b should be used (combine).
Copy code
val a = flow {
    var counter = 0
    while (true) {
        emit(counter)
        counter++
        delay(1.seconds)
    }
}

val b = flow {
    delay(2.seconds)
    emit("a")
    delay(2.seconds)
    emit("b")
    delay(2.seconds)
}

val expected = listOf(1 to null, 2 to null, 3 to null, 4 to "a", 5 to "a", 6 to "b", 7 to "b")
j
First thing that comes to mind is to use
.onStart { emit(null) }
on
b
to ensure you get the first (null) value of
b
to combine with all first values of
a
- didn't think it through but I think it should work
e
.onStart { emit(null) }
should work with `.combine()`; not
.zip()
of course
j
oops, forgot
emit
h
Ohh, nice. I thought onStart will only be called once.
e
it is called only once (per subscribe)
it's combine that's re-using values when the two flows are producing at different times
1
h
Thanks!
j
Note that you'll probably need to make
b
a
Flow<String?>
up front for
onStart
to be able to emit
null
h
Yeah, thats true, I use a simple
map
👍 1