本片文章主要介绍Flow上下游处理,上游一个Flow使用map,上游两个Flow使用zip,上游三个Flow及以上使用combine
1、下面代码展示了upStreamFlow作为上游,downStreamFlow作为下游,通过对upStreamFlow使用map操作符函数将upStreamFlow转换为新的Flow对象,每个元素都通过lambda表达式进行处理,并生成以“Number:”为开头的字符串。
package com.cqz
import kotlinx.coroutines.flow.*
suspend fun main() {
val upStreamFlow: Flow = flow {
for (i in 1..5) {
emit(i)
}
}
val downStreamFlow: Flow = upStreamFlow.map {
"Number:$it"
}
upStreamFlow.collect {
println("upStreamFlow:$it")
}
downStreamFlow.collect {
println("downStreamFlow:$it")
}
}
运行以上代码将会得到以下结果
upStreamFlow:1
upStreamFlow:2
upStreamFlow:3
upStreamFlow:4
upStreamFlow:5
downStreamFlow:Number:1
downStreamFlow:Number:2
downStreamFlow:Number:3
downStreamFlow:Number:4
downStreamFlow:Number:5
2、上游两个Flow可以使用zip操作符函数将两个Flow合并为新的Flow对象。这个函数接受两个asdFlow作为参数,并通过lambda表达式将它们的元素进行组合。
package com.cqz
import kotlinx.coroutines.flow.*
suspend fun main() {
val upStreamFlow: Flow = flow {
for (i in 1..5) {
emit(i)
}
}
val upStream2Flow: Flow = flow {
for (i in 6..10) {
emit(i)
}
}
upStreamFlow.zip(upStream2Flow) { num1,num2->
num1 + num2
}.collect {
println("zip:$it")
}
}
运行以上代码将会得到以下结果
zip:7
zip:9
zip:11
zip:13
zip:15
3、上游有三个Flow或以上的时候可以使用combine操作符函数,将三个Flow合并为一个Flow
package com.cqz
import kotlinx.coroutines.flow.*
suspend fun main() {
val flow1 = flowOf(1,2,3)
val flow2 = flowOf(false,true,false)
val flow3 = flowOf("A","B","C")
val combinedFlow = combine(flow1,flow2,flow3) {i, b, s ->
CombinedResult(i,b,s)
}
combinedFlow.collect {
println("combinedFlow:$it")
}
}
data class CombinedResult(val i: Int,val b: Boolean,val str: String)
运行以上代码将会得到以下结果
combinedFlow:CombinedResult(i=1, b=false, str=A)
combinedFlow:CombinedResult(i=2, b=false, str=A)
combinedFlow:CombinedResult(i=2, b=true, str=A)
combinedFlow:CombinedResult(i=2, b=true, str=B)
combinedFlow:CombinedResult(i=3, b=true, str=B)
combinedFlow:CombinedResult(i=3, b=false, str=B)
combinedFlow:CombinedResult(i=3, b=false, str=C)