心里种花,人生才不会荒芜,如果你也想一起成长,请点个关注吧。
Kotlin 的 Flow 提供了一系列操作符,这些操作符类似于 RxJava,但更加简洁和易于使用。以下是一些常用的 Flow 操作符,分为不同类别:
1、 map:
flowOf(1, 2, 3).map { it * 2 } // Produces 2, 4, 6
2、 filter:
flowOf(1, 2, 3).filter { it % 2 == 0 } // Produces 2
3、 transform:
flowOf(1, 2, 3).transform { emit(it * 2); emit(it + 1) } // Produces 2, 2, 4, 3, 6, 4
4、 scan:
flowOf(1, 2, 3).scan(0) { acc, value -> acc + value } // Produces 0, 1, 3, 6
1、 filterNot:
flowOf(1, 2, 3).filterNot { it % 2 == 0 } // Produces 1, 3
2、 take:
flowOf(1, 2, 3).take(2) // Produces 1, 2
3、 drop:
flowOf(1, 2, 3).drop(2) // Produces 3
1、 reduce:
flowOf(1, 2, 3).reduce { acc, value -> acc + value } // Produces 6
2、 fold:
reduce 类似,但需要一个初始值。flowOf(1, 2, 3).fold(10) { acc, value -> acc + value } // Produces 16
1、 flatMapConcat:
flowOf(1, 2).flatMapConcat { flowOf(it, it + 1) } // Produces 1, 2, 2, 3
2、 flatMapMerge:
flowOf(1, 2).flatMapMerge { flowOf(it, it + 1) } // Produces 1, 2, 2, 3 (Order may vary)
3、 flatMapLatest:
flowOf(1, 2).flatMapLatest { flowOf(it, it + 1) } // Produces 2, 3 (Flattens the last emitted item only)
1、 catch:
flow {
emit(1)
throw RuntimeException("Error")
}.catch { e -> emit(-1) } // Produces 1, -1
2、 retry:
flow {
emit(1)
throw RuntimeException("Error")
}.retry(3) // Tries to retry 3 times on error
1、 collect:
flowOf(1, 2, 3).collect { println(it) } // Prints 1, 2, 3
2、 first:
val firstElement = flowOf(1, 2, 3).first() // 1
3、 toList:
val list = flowOf(1, 2, 3).toList() // [1, 2, 3]
1、 buffer:
flow {
emit(1)
emit(2)
}.buffer().collect { println(it) } // Prints 1, 2
2、 conflate:
flow {
emit(1)
emit(2)
emit(3)
}.conflate().collect { println(it) } // Prints 3
3、 collectLatest:
flow {
emit(1)
delay(100)
emit(2)
}.collectLatest { value ->
delay(50)
println(value)
} // Only the latest emitted item will be printed
1、 debounce:
flow {
emit(1)
delay(100)
emit(2)
delay(100)
emit(3)
}.debounce(150) // Only emits 3
2、 timeout:
flowOf(1, 2, 3).timeout(100) // Throws TimeoutCancellationException
这些操作符使得 Kotlin Flow 成为一个强大且灵活的数据流处理工具,能够处理各种应用场景中的异步数据流。通过合理使用这些操作符,你可以构建出高效且可维护的流数据处理逻辑。