I have a `List` of `Flow`s which I combine into a ...
# coroutines
m
I have a
List
of `Flow`s which I combine into a single
Flow
using
combine(Iterable)
. Now I want to add another
Flow
to the
List
. How to handle this? Keep a reference to the combine
Job
and cancel/recreate accordingly? Combine the existing
combine
Flow
with the new
Flow
list item? Or perhaps represent the list as a
Flow
and use
runningFold
and
flatMapLatest
? Something else?
o
At what point do you want to add another flow? After the combine? Is it not possible to add it upstream with the original list?
m
I have a
MutableList
of items where each item is represented by a
Flow
. So I combine these `Flow`s into one
Flow
. The items are being appended to as the user scrolls down and so at this point I need to recreate the combined flow. I’m just wondering the best way to do this.
o
Then I suppose a single flow runningFold would be most suited for this situation. Or any other operator that can give you the latest item plus previous combination.
m
I ended up replacing the
MutableList
with a
MutableStateFlow
starting with an empty list, and using
update
whenever I wanted to add a new item. Then I use
flatMapLatest
and
combine
to get the flow I need. Note: it’s important to not use
combine
when the list is empty. Something like this:
Copy code
val itemsStateFlow = MutableStateFlow(emptyList<Item>())

fun addItem(item: Item) {
    itemsStateFlow.update { it + item }
}

val resultsFlow: StateFlow<Foo> = itemsStateFlow.flatMapLatest { items ->
    if (items.isEmpty()) {
        flowOf(Foo(emptyList()))
    } else {
        combine(items.map(Item::flow)) {
            Foo(it)
        }
    }
}.stateIn(coroutineScope, SharingStarted.Eagerly, Foo(emptyList())
204 Views