kotlinkotlin-coroutineskotlin-flow

How to concatenate two kotlin flows?


As stated, I'd like to concatenate two flows sequentially therefore merge won't work.

Example:

val f1 = flowOf(1, 2)
val f2 = flowOf(3, 4)
val f = concatenate(f1, f2) // emits 1, 2, 3, 4


Solution

  • You can use flattenConcat for this:

    fun <T> concatenate(vararg flows: Flow<T>) =
        flows.asFlow().flattenConcat()
    

    Or the flow builder:

    fun <T> concatenate(vararg flows: Flow<T>) = flow {
        for (flow in flows) {
            emitAll(flow)
        }
    }