5

我正在寻找组合 4 个 StateFlow 值并从中生成 1 个 StateFlow。我已经知道这样的组合功能:

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

这怎么能用 4 个流来完成?当我尝试以下操作时,我得到了参数太多的错误,但是组合函数文档确实说你最多可以添加 5 个流?

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

}
4

1 回答 1

12

“但合并功能文档确实说您最多可以添加 5 个流?”

是的语法:

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

如果您需要超过 5 个组合,那么为 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
    )
}
于 2021-06-11T15:26:55.763 回答