Search code examples
androidkotlinandroid-roomkotlin-coroutineskotlin-flow

Chaining and mapping kotlin flow


I'm trying to get a result from a flow, that retrieves a list from a room database, and then trying to map the list with another flow inside from another database operation, but I don't know if it is possible and if it is, how to make it, at this time I'm trying to make something like this

fun retrieveOperationsWithDues(client: Long): Flow<List<ItemOperationWithDues>> {
    return database.operationsDao.getOperationCliente(client)
        .flatMapMerge {
            flow<List<ItemOperationWithDues>> {
                it.map { itemOperation ->
                    database.duesDao.cuotasFromOperation(client, itemOperation.id).collectLatest { listDues ->
                        itemOperation.toItemOperationWithDues(listDues)
                    }
                }
            }
        }
}

but looks like is not retrieving anything from the collect. Thanks in advice for any help


Solution

  • I think you don't need to use flow builder in flatMapMerge block. For each itemOperation you can call the cuotasFromOperatio() function from the Dao, which returns Flow and use combine() to combine retrieved flows:

    fun retrieveOperationsWithDues(client: Long): Flow<List<ItemOperationWithDues>> {
        return database.operationsDao.getOperationCliente(client)
            .flatMapMerge {
                val flows = it.map { itemOperation ->
                    database.duesDao.cuotasFromOperation(client, itemOperation.id).map { listDues ->
                        itemOperation.toItemOperationWithDues(listDues)
                    }
                }
                combine(flows) { flowArray -> flowArray.toList() }
            }
    }