簡體   English   中英

合並多個 Flow <list<t> &gt; 單流<map<string, list<t> &gt;&gt; </map<string,></list<t>

[英]Combine multiple Flow<List<T>> to a Single Flow<Map<String, List<T>>>

我正在嘗試將來自 Room 數據庫上不同 @Query 的多個流結果轉換為這些結果列表的 Map 流。 像這樣的東西:

 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))  }

收集器中的 output 用於combine (組合來自任一流的最新值):

{A=[1], B=[2]}

{A=[1], B=[3]}

zip 的收集器中的zip (壓縮每個流的排放對):

{A=[1], B=[2]}

更新

在使用了 api 之后,您可以使用combine可以占用nFlow<T>

val flowA =  flow<Int> { emit(1) }
val flowB =  flow<Int> { emit(2) }
val flowC =  flow<Int> { emit(3) }
    
combine(flowA, flowB, flowC, ::Triple)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM