Kotlin组合了2个以上的流量



我希望将4个StateFlow值组合起来,并从中生成1个StateFlow。我已经知道这样的联合功能:

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

如何使用4个流来实现这一点?当我尝试以下操作时,我得到的错误是参数太多了,但组合函数文档确实说你最多可以添加5个流?

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

"但是combine函数文档确实说你最多可以加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
)
}

如果您需要组合多个相同类型的流,而不考虑长度,

可以使用此方法创建

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

相关内容

最新更新