Home > OS >  Chaining and mapping kotlin flow
Chaining and mapping kotlin flow

Time:05-28

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

CodePudding user response:

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() }
        }
}
  • Related