Home > Blockchain >  Collect list of stateFLow
Collect list of stateFLow

Time:02-21

I have a list of integer state flows.

listOfFlows : List<StateFlow<Int>> 

And i need a single state flow that would be a sum of the list state flows.

sum: StateFlow<Int>

How i can do that?

CodePudding user response:

You could use combine to create a flow that emits the sum of all current values of the source flows each time one of them emits:

val sumFlow = combine(stateFlows) { it.sum() }

And if you really need a StateFlow as a result, you can use stateIn:

val sumFlow = combine(stateFlows) { it.sum() }
val sumStateFlow = sumFlow.stateIn(someScope)
  • Related