Home > Enterprise >  Combine many Kotlin flows to get just their current value
Combine many Kotlin flows to get just their current value

Time:12-08

I'm using the Preference APIs that return flows. There are cases when I need to combine values from different preferences. I know I can use flow.combine.

Since the method where I need to combine is a suspend function and the value from the flows do not need to flow anywhere anymore, I could also define something like this:

suspend fun <T> Flow<T>.currentValue(): T {
    var res: T? = null
    this.collect {
        res = it
    }
    return res!!
}

and then just read one value at at time:

    val val1 = flow1.currentValue()
    val val2 = flow2.currentValue()
    val val3 = flow3.currentValue()

Is there a better way to do it? Or should I just use the combine method?

CodePudding user response:

You don't need to define a currentValue function. There is already a Flow.first() function that returns the first value of the Flow. Since these Flows are designed to always emit an initial value with the current value of the preference, this will work fine.

Side note, your currentValue() function will never return because collect doesn't return until the Flow is complete.

Whether you want to individually call first() on each Flow or combine all of them and call first() on the combined Flow is up to you. I don't think it's any cleaner either way.

  • Related