20

I'm looking to combine 4 StateFlow values and make 1 StateFlow from these. I know already of the combine function like this:

val buttonEnabled = cameraPermission.combine(micPermission) {
    //some logic
}

How could this be done with 4 flows? when I attempt the below, I get the error there is too many arguments, but the combine function docs do say you are able to add up to 5 flows?

val buttonEnabled = cameraPermission.combine(micPermission, locationPermission, contactsPermission) {

}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
alfietap
  • 1,585
  • 1
  • 15
  • 38

2 Answers2

44

"but the combine function docs do say you are able to add up to 5 flows?"

Yes syntax :

combine(flow1, flow2, flow3, flow4) {t1, t2, t3, t4 -> resultMapper}.stateIn(scope)

If you require more than 5 combined, then it is very simple to create your own functions example for 6 :

fun <T1, T2, T3, T4, T5, T6, R> combine(
    flow: Flow<T1>,
    flow2: Flow<T2>,
    flow3: Flow<T3>,
    flow4: Flow<T4>,
    flow5: Flow<T5>,
    flow6: Flow<T6>,
    transform: suspend (T1, T2, T3, T4, T5, T6) -> R
): Flow<R> = combine(
    combine(flow, flow2, flow3, ::Triple),
    combine(flow4, flow5, flow6, ::Triple)
) { t1, t2 ->
    transform(
        t1.first,
        t1.second,
        t1.third,
        t2.first,
        t2.second,
        t2.third
    )
}
Mark
  • 9,604
  • 5
  • 36
  • 64
0

if you need to combine multiple same type flow regardless of length,

you can use this method to create

class Util {
    companion object {
        fun <T> getMultipleCombinedFlow(vararg flow: Flow<T>, transform: (T, T) -> T): Flow<T> {
            return combineMultiple(flow, 0, null, transform)
        }

        private fun <T> combineMultiple(
            array: Array<out Flow<T>>,
            index: Int = 0,
            combined: Flow<T>? = null,
            transform: (T, T) -> T
        ): Flow<T> {
            if (array.size == 1) {
                return array[0]
            }
            if (index >= array.size)
                return combined!!

            if (combined == null) {
                val result = array[index].combine(array[index + 1], transform)
                return combineMultiple(array, index + 2, result, transform)
            }

            val result = combined.combine(array[index], transform)
            return combineMultiple(array, index + 1, result, transform)

        }
    }
}
Moon
  • 3
  • 2