What's the difference between using flatMap and combine a list of flows?

315 views Asked by At

I have been writing some handling for my flows interchangeably in my codebase, especially in my Usecases and repositories. I would like to get some insight into what would be the better approach, and why, between the two solutions below. What I am looking for in the end is to go from Flow<List<ItemInfo>> to Flow<List<Item>> where any changes to the Item in the ItemRepo will update the flow - i.e it uses a function call that returns Flow<Item>.

Repository functions:

InfoRepo.homeItems() : Flow<List<ItemInfo>>
ItemRepo.getItem(info: ItemInfo): Flow<Item>

On my home screen, I want to display all items available so in my use case I can do either:

infoRepo.homeItems().flatMapLatest { homeList ->
    val listOfFlows = homeList.map { itemRepo.getItem(it) } // List<Flow<Item>>
    combine (listOfFlows) { array -> array.toList() } // assumes list never empty
}

OR

infoRepo.homeItems().map { homeList ->
    homeList.asFlow().flatMapConcat { bulletRepo.observeBullet(it) }.toList()
}

I have a utility function List<Flow<T>>.combineToList(): Flow<List<T>> that does the combine(list){ it.toList() } for me.

Which of these two are more performant, less error prone and works as mostly expected? Or is it just flavour, is it neither?

0

There are 0 answers