将多个流<列表<T>>合并为单个流<映射<字符串、列表<T>>>



我正在尝试将房间数据库上不同@Query的多个流结果转换为这些结果列表的地图流。像这样:

fun getA(): Flow<List<T>> // query 1
fun getB(): Flow<List<T>>// query 2

我尝试做这样的事情:

fun getMappedList(): Flow<Map<String, List<T>>> {
val mapList = mutableMapOf<String, List<T>>()

return flow {
getA().map{
mapList["A"] = it
}
getB().map{
mapList["B"] = it
}
emit(mapList)
}

}

但显然,这似乎行不通。任何想法我如何实现这一目标。提前非常感谢

我并没有真正使用Flowapi,但是这样的事情应该可以工作:

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(每个流的 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)

最新更新