Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin combine more than 2 flows

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) {

}
like image 425
alfietap Avatar asked Sep 07 '25 22:09

alfietap


1 Answers

"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
    )
}
like image 195
Mark Avatar answered Sep 10 '25 12:09

Mark