https://kotlinlang.org logo
#compose
Title
# compose
a

Alexander Maryanovsky

06/06/2022, 8:01 AM
What is the correct way to combine several `StateFlow`s and display the resulting value in Compose?
m

myanmarking

06/06/2022, 8:21 AM
combine?
x

xxfast

06/06/2022, 8:25 AM
Also, don't do it inside of a
@Composable
, do it elsewhere (maybe
ViewModel)
a

Alexander Maryanovsky

06/06/2022, 8:31 AM
combine gives me a regular Flow
b

Bwaim

06/06/2022, 9:36 AM
then you can use the
stateIn
operator on Flow
a

Alexander Maryanovsky

06/06/2022, 11:37 AM
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

Stylianos Gakis

06/06/2022, 12:13 PM
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

Alexander Maryanovsky

06/06/2022, 12:24 PM
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

Stylianos Gakis

06/06/2022, 1:30 PM
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

Alexander Maryanovsky

06/06/2022, 1:34 PM
Yes, that’s exactly the helper function.
🦜 1
24 Views