You can choose to mix multiple streams.
Use the function merge
or combine
in kotlin
. Of course, the usage of these two functions is different.
Add:
If Flow is not processed, open multiple Coroutines to 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)
}
}
Open two coroutine collections
result is:
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
Merge two flows
fun margeFlow() = runBlocking {
merge(
emitIntElem().map {
it.toString()
}, emitStringElem()
).collect {
println(it)
}
}
result is :
0
elem_0
1
elem_1
2
elem_2
3
elem_3
4
elem_4
5
6
7
8
9
conbine two flows:
fun combineFlow() = runBlocking {
combine(emitIntElem(), emitStringElem()) { int: Int, str: String ->
"$int combine $str"
}.collect {
println(it)
}
}
result is:
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