Home > Software engineering >  How to concat multiple Kotlin Flows sequencially?
How to concat multiple Kotlin Flows sequencially?

Time:04-03

I'm looking for a way to subscribe to multiple Kotlin Flows sequencially, something similar to rxjs's concat operator. Next Flow should only be subscribed once previous one is completed.

Example:

val flow1 = flowOf(0,1,2).onEach { delay(10) }
val flow2 = flowOf(3,4,5).onEach { delay(10) }

runBlocking{
    listOf(flow1,flow2)
        .merge()
        .onEach { println(it) }
        .collect()
}

-> prints 0,3,1,4,2,5 // Flow order is not preserved

I imagine a solution could be to replace merge() with concat(), but this operator sadly doesn't exist in Kotlin Flows

val flow1 = flowOf(0,1,2).onEach { delay(10) }
val flow2 = flowOf(3,4,5).onEach { delay(10) }

runBlocking{
    listOf(flow1,flow2)
        .concat()
        .onEach { println(it) }
        .collect()
}

-> prints 0,1,2,3,4,5 // Flow order is now preserved

CodePudding user response:

You're looking for flattenConcat.

It has a Flow<Flow<T>> receiver, but you could easily make a Flow out of your list of flows, for instance using list.asFlow(). Or you could create a Flow directly instead of a list by using flowOf instead of listOf.

  • Related