Sergey Alaev
Sergey Alaev

Reputation: 3962

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

Upvotes: 4

Views: 4187

Answers (2)

Tenfour04
Tenfour04

Reputation: 93511

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)
    }
}

Upvotes: 10

bylazy
bylazy

Reputation: 1295

This should work: onCompletion

val f1 = flowOf(1,2,3)
val f2 = flowOf(4,5,6)
val f = f1.onCompletion{emitAll(f2)}
runBlocking {
   f.collect {
        println(it)
   }
}

//Result: 1 2 3 4 5 6

Upvotes: 2

Related Questions