'Combine values of multiple kotlin flows even if only some emit values

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source