What is the correct way to combine several `StateF...
# compose
a
What is the correct way to combine several `StateFlow`s and display the resulting value in Compose?
m
combine?
x
Also, don't do it inside of a
@Composable
, do it elsewhere (maybe
ViewModel)
a
combine gives me a regular Flow
b
then you can use the
stateIn
operator on Flow
a
That forces me to provide an initial value, which if wrong, will still be displayed for a split-second.
I did end up using
stateIn
, but I wrote a helper
combineStateFlows
function which takes `StateFlow`s and a transform function, and sets the initial value to the transform of the state flow’s values at the time of the call.
Which is either a bad idea for some reason I don’t quite understand, or is strange for not being included.
s
Combining stateflows needs to know in which coroutineScope it needs to be doing this combining work since the lambda passed inside the combine function is suspending. My guess is that it’s not “included” since there’s no super simple API that would achieve that, plus it’s trivial to do by yourself. Doing something like this
Copy code
val one: StateFlow<String>
val two: StateFlow<String>

val state = combine(one, two) { one, two ->
    one to two
}.stateIn(
    viewModelScope,
    SharingStarted.WhileSubscribed(5.seconds),
    one.value to two.value,
)
is perfectly fine, I don’t think it’s a bad idea.
a
Now imagine you have UI displaying 20 of those, and the transform functions much more complicated. But yeah, the helper function isn't hard.
s
Yeah it’s probably not the prettiest thing in the world. But you can probably extract this mapping function somewhere and use it inside the combine lambda with the variables you’re receiving, and use the same function in the initialValue but by now using the
.value
on all StateFlows instead.
a
Yes, that’s exactly the helper function.
🦜 1