我正在尝试将 Room 数据库上不同 @Query 的多个 Flow 结果转换为这些结果列表的 Map Flow。像这样的事情:
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)
}
}
但显然这似乎不起作用。我有什么想法可以实现这一点。非常感谢提前
最佳答案
我还没有真正使用过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)
关于android - 将多个 Flow<List<T>> 合并为单个 Flow<Map<String, List<T>>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62681501/