-
處理最新值
當發射器和收集器都很慢的時候,合并是加快處理速度的一種方式。它通過刪除發射值來實現。 另一種方式是取消緩慢的收集器,并在每次發射新值的時候重新啟動它。有一組與 xxx
操作符執行相同基本邏輯的 xxxLatest
操作符,但是在新值產生的時候取消執行其塊中的代碼。讓我們在先前的示例中嘗試更換 [conflate]
val time = measureTimeMillis {
simple()
.collectLatest { value -> // 取消并重新發射最后一個值
println("Collecting $value")
delay(300) // 假裝我們花費 300 毫秒來處理它
println("Done $value")
}
}
println("Collected in $time ms")
Collecting 1
Collecting 2
Collecting 3
Done 3
Collected in 680 ms
-
組合多個流
Zip
就像 Kotlin 標準庫中的 Sequence.zip 擴展函數一樣, 流擁有一個 zip 操作符用于組合兩個流中的相關值:
val nums = (1..3).asFlow() // 數字 1..3
val strs = flowOf("one", "two", "three") // 字符串
nums.zip(strs) { a, b -> "$a -> $b" } // 組合單個字符串
.collect { println(it) } // 收集并打印
1 -> one
2 -> two
3 -> three
Combine
當流表示一個變量或操作的最新值時,可能需要執行計算,這依賴于相應流的最新值,并且每當上游流產生值的時候都需要重新計算。這種相應的操作符家族稱為 [combine]
例如,先前示例中的數字如果每 300 毫秒更新一次,但字符串每 400 毫秒更新一次, 然后使用 操作符合并它們,但仍會產生相同的結果, 盡管每 400 毫秒打印一次結果:
val nums = (1..3).asFlow().onEach { delay(300) } // 發射數字 1..3,間隔 300 毫秒
val strs = flowOf("one", "two", "three").onEach { delay(400) } // 每 400 毫秒發射一次字符串
val startTime = System.currentTimeMillis() // 記錄開始的時間
nums.zip(strs) { a, b -> "$a -> $b" } // 使用“zip”組合單個字符串
.collect { value -> // 收集并打印
println("$value at ${System.currentTimeMillis() - startTime} ms from start")
}
1 -> one at 427 ms from start
2 -> two at 827 ms from start
3 -> three at 1229 ms from start
然而,當在這里使用 [combine]操作符來替換 [zip]
val nums = (1..3).asFlow().onEach { delay(300) } // 發射數字 1..3,間隔 300 毫秒
val strs = flowOf("one", "two", "three").onEach { delay(400) } // 每 400 毫秒發射一次字符串
val startTime = System.currentTimeMillis() // 記錄開始的時間
nums.combine(strs) { a, b -> "$a -> $b" } // 使用“combine”組合單個字符串
.collect { value -> // 收集并打印
println("$value at ${System.currentTimeMillis() - startTime} ms from start")
}
1 -> one at 452 ms from start
2 -> one at 651 ms from start
2 -> two at 854 ms from start
3 -> two at 952 ms from start
3 -> three at 1256 ms from start
-
展平流
流表示異步接收的值序列,所以很容易遇到這樣的情況: 每個值都會觸發對另一個值序列的請求。比如說,我們可以擁有下面這樣一個返回間隔 500 毫秒的兩個字符串流的函數
fun requestFlow(i: Int): Flow<String> = flow {
emit("$i: First")
delay(500) // 等待 500 毫秒
emit("$i: Second")
}
現在,如果我們有一個包含三個整數的流,并為每個整數調用 requestFlow,如下所示:
(1..3).asFlow().map { requestFlow(it) }
然后我們得到了一個包含流的流(Flow<Flow<String>>
),需要將其進行展平為單個流以進行下一步處理。集合與序列都擁有 [flatten]與 [flatMap] 操作符來做這件事。然而,由于流具有異步的性質,因此需要不同的展平模式, 為此,存在一系列的流展平操作符。
flatMapConcat
連接模式由 [flatMapConcat]與 [flattenConcat]操作符實現。它們是相應序列操作符最相近的類似物。它們在等待內部流完成之前開始收集下一個值,如下面的示例所示:
al startTime = System.currentTimeMillis() // 記錄開始時間
(1..3).asFlow().onEach { delay(100) } // 每 100 毫秒發射一個數字
.flatMapConcat { requestFlow(it) }
.collect { value -> // 收集并打印
println("$value at ${System.currentTimeMillis() - startTime} ms from start")
}
1: First at 121 ms from start
1: Second at 622 ms from start
2: First at 727 ms from start
2: Second at 1227 ms from start
3: First at 1328 ms from start
3: Second at 1829 ms from start
在輸出中可以清楚地看到 [flatMapConcat] 的順序性質:
flatMapMerge
另一種展平模式是并發收集所有傳入的流,并將它們的值合并到一個單獨的流,以便盡快的發射值。 它由 [flatMapMerge] 與 [flattenMerge]操作符實現。他們都接收可選的用于限制并發收集的流的個數的 concurrency
參數(默認情況下,它等于 [DEFAULT_CONCURRENCY]。
val startTime = System.currentTimeMillis() // 記錄開始時間
(1..3).asFlow().onEach { delay(100) } // 每 100 毫秒發射一個數字
.flatMapMerge { requestFlow(it) }
.collect { value -> // 收集并打印
println("$value at ${System.currentTimeMillis() - startTime} ms from start")
}
1: First at 150 ms from start
2: First at 246 ms from start
3: First at 347 ms from start
1: Second at 651 ms from start
2: Second at 747 ms from start
3: Second at 849 ms from start
[flatMapMerge]的并發性質很明顯:
flatMapLatest
與 collectLatest 操作符類似(在"處理最新值" 小節中已經討論過),也有相對應的“最新”展平模式,在發出新流后立即取消先前流的收集。 這由 flatMapLatest 操作符來實現。
val startTime = System.currentTimeMillis() // 記錄開始時間
(1..3).asFlow().onEach { delay(100) } // 每 100 毫秒發射一個數字
.flatMapLatest { requestFlow(it) }
.collect { value -> // 收集并打印
println("$value at ${System.currentTimeMillis() - startTime} ms from start")
}
1: First at 225 ms from start
2: First at 357 ms from start
3: First at 458 ms from start
3: Second at 959 ms from start
該示例的輸出很好的展示了 [flatMapLatest]的工作方式:
在一個新值到來時取消了塊中的所有代碼 (本示例中的 { requestFlow(it) })。 這在該特定示例中不會有什么區別,由于調用 requestFlow 自身的速度是很快的,不會發生掛起, 所以不會被取消。然而,如果我們要在塊中調用諸如 delay 之類的掛起函數,這將會被表現出來。
總結Flow 關鍵字
- asFlow
- flowOf
- flow{...}
- withTimeoutOrNull
- 操作符,take, map,reduce,filter,transform,toList,collect,toSet,first,single,reduce,fold,
flowOn,conflate,collectLatest,Combine
flatMap,flatMapConcat,flatten,flatMapMerge,flatMapLatest