我并没有真正使用过这个Flow
api,但是这样的东西应该可以工作:
fun getMappedList(): Flow<Map<String, List<Int>>>
= getA().combine(getB()) { a, b -> mapOf(Pair("A", a), Pair("B", b)) }
或者根据您的用例,您可能希望使用zip
运算符,作为唯一的“对”发出:
fun getMappedList(): Flow<Map<String, List<Int>>>
= getA().zip(getB()) { a, b -> mapOf(Pair("A", a), Pair("B", b)) }
测试使用:
fun getA(): Flow<List<Int>> = flow { emit(listOf(1)) }
fun getB(): Flow<List<Int>> = flow { emit(listOf(2)); emit(listOf(3)) }
fun getCombine(): Flow<Map<String, List<Int>>>
= getA().combine(getB()) { a, b -> mapOf(Pair("A", a), Pair("B", b)) }
fun getZip(): Flow<Map<String, List<Int>>>
= getA().zip(getB()) { a, b -> mapOf(Pair("A", a), Pair("B", b)) }
收集器中的输出combine
(组合来自任一流的最新值):
{A=[1], B=[2]}
{A=[1], B=[3]}
收集器中的输出zip
(压缩每个流的排放对):
{A=[1], B=[2]}
更新
使用 api 多一点后,您可以使用combine
它,它可以占用以下n
数量Flow<T>
:
val flowA = flow<Int> { emit(1) }
val flowB = flow<Int> { emit(2) }
val flowC = flow<Int> { emit(3) }
combine(flowA, flowB, flowC, ::Triple)