您可以选择混合多个流。
使用函数merge
或combine
在kotlin
. 当然,这两个函数的用法是不一样的。
添加:
如果 Flow 没有被处理,打开多个 Coroutine 去 collect():
fun main() {
collectFlow()
}
fun emitStringElem(): Flow<String> = flow {
repeat(5) {
delay(10)
emit("elem_$it")
}
}
fun emitIntElem(): Flow<Int> = flow {
repeat(10) {
delay(10)
emit(it)
}
}
打开两个协程集合结果是:
From int Flow: item is: 0
From string Flow: item is: elem_0
From int Flow: item is: 1
From string Flow: item is: elem_1
From int Flow: item is: 2
From string Flow: item is: elem_2
From int Flow: item is: 3
From string Flow: item is: elem_3
From int Flow: item is: 4
From string Flow: item is: elem_4
From int Flow: item is: 5
From int Flow: item is: 6
From int Flow: item is: 7
From int Flow: item is: 8
From int Flow: item is: 9
合并两个流
fun margeFlow() = runBlocking {
merge(
emitIntElem().map {
it.toString()
}, emitStringElem()
).collect {
println(it)
}
}
结果是:
0
elem_0
1
elem_1
2
elem_2
3
elem_3
4
elem_4
5
6
7
8
9
合并两个流程:
fun combineFlow() = runBlocking {
combine(emitIntElem(), emitStringElem()) { int: Int, str: String ->
"$int combine $str"
}.collect {
println(it)
}
}
结果是:
0 combine elem_0
1 combine elem_0
1 combine elem_1
2 combine elem_2
3 combine elem_3
4 combine elem_4
5 combine elem_4
6 combine elem_4
7 combine elem_4
8 combine elem_4
9 combine elem_4