android - 将多个 Flow<List<T>> 合并为单个 Flow<Map<String, List<T>>>

标签 android kotlin-coroutines kotlin-flow

我正在尝试将 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/

相关文章:

kotlin - Flow<List<T>> 而不是使用 Flow<T>?

android - 单元测试新的 Kotlin 协程 StateFlow

android - 如何使用 Flows 处理数据库调用错误

android - 如何使我的微调器目标链接到网站?

unit-testing - 当使用返回流的存储库对 View 模型进行单元测试时,将其转换为实时数据时会发生错误

java - 如何为 Retrofit 中的挂起功能创建调用适配器?

kotlin - 使用调度程序运行异步 Kotlin 代码

java - 将方法实现到按钮监听器中时出错

android - 在 WebView Android 中启用缩放选项

kotlin - 异步中的 withContext