八. Flow 其他的操作符
8.1 Transform operators
transform
在使用 transform 操作符时,可以任意多次调用 emit ,这是 transform 跟 map 最大的区别:
fun main() = runBlocking {
(1..5).asFlow()
.transform {
emit(it * 2)
delay(100)
emit(it * 4)
}
.collect { println(it) }
}
transform 也可以使用 emit 发射任意值:
fun main() = runBlocking {
(1..5).asFlow()
.transform {
emit(it * 2)
delay(100)
emit("emit $it")
}
.collect { println(it) }
}
8.2 Size-limiting operators
take
take 操作符只取前几个 emit 发射的值。
fun main() = runBlocking {
(1..5).asFlow()
.take(2)
.collect { println(it) }
}
8.3 Terminal flow operators
在 Kotlin Coroutines Flow 系列(一) Flow 基本使用 一文最后,我整理了 Flow 相关的 Terminal 操作符。本文介绍 reduce 和 fold 两个操作符。
reduce
类似于 Kotlin 集合中的 reduce 函数,能够对集合进行计算操作。
例如,对平方数列求和:
fun main() = runBlocking {
val sum = (1..5).asFlow()
.map { it * it }
.reduce { a, b -> a + b }
println(sum)
}
例如,计算阶乘:
fun main() = runBlocking {
val sum = (1..5).asFlow().reduce { a, b -> a * b }
println(sum)
}
fold
也类似于 Kotlin 集合中的 fold 函数,fold 也需要设置初始值。
fun main() = runBlocking {
val sum = (1..5).asFlow()
.map { it * it }
.fold(0) { a, b -> a + b }
println(sum)
}
在上述代码中,初始值为0就类似于使用 reduce 函数实现对平方数列求和。
而对于计算阶乘:
fun main(