0

I am trying to combine multiple flows even if some of them don't emit.

I tried to create a reproducible snippet to be able to illustrate better what I want to achieve. Below you can see my 2 attempts, but non of them work as expected.

fun main() {

    val ids = (1..5)
    val idsFlow = ids.asFlow()

    //option 1
    println("Option 1")
    val valuesFlow = idsFlow.map { id ->
        getFlowById(id)
    }.flattenMerge()

    runBlocking {
        valuesFlow.collect { listOfItems ->
            println("Value received $listOfItems")
        }
    }

    //option 2
    println("Option 2")
    val valuesFlowList = ids.map { id ->
        getFlowById(id)
    }

    runBlocking {
        combine(valuesFlowList) { itemsLists ->
            itemsLists.flatMap { it }
        }.collect { listOfItems ->
            println("Value received $listOfItems")
        }
    }

}

fun getFlowById(id: Int): Flow<List<Int>> = flow {
    println("Flow for id $id")
    if (id % 2 == 0) {
        emit(listOf(id, id))
    }
}

And the output of this is:

Option 1
Flow for id 1
Flow for id 2
Flow for id 3
Flow for id 4
Flow for id 5
Value received [2, 2]
Value received [4, 4]
Option 2
Flow for id 1
Flow for id 2
Flow for id 3
Flow for id 4
Flow for id 5

Process finished with exit code 0

But what I would like to end up with is:

Value received [2, 2, 4, 4]

I believe I am missing something, but not sure what. If someone could point me to the right direction it would be really appreciated.

amp
  • 11,754
  • 18
  • 77
  • 133
  • @Tenfour04 That doesn't fix it. I still don't get the list of all the elements. The difference is that with `flattenConcat` it collects right after it is emited – amp Jan 24 '22 at 17:24
  • So right now you are flattening into a `Flow>` but you want the Flow to produce only a single List that is a concatenated list of all values from the source flow? Your desired output above is a Flow of a single List. Seems like an odd requirement. – Tenfour04 Jan 24 '22 at 18:35
  • Please see this answer https://stackoverflow.com/a/70710723/1731626, maybe it will help. – Sergio Jan 24 '22 at 19:05

0 Answers0