1

我正在尝试将来自 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)
      }
    
    }

但显然这似乎行不通。任何想法我如何能做到这一点。提前谢谢了

4

1 回答 1

1

我并没有真正使用过这个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(压缩每个流的排放对):

{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)
于 2020-07-01T18:36:51.410 回答