Skip to content

Commit 95a24a5

Browse files
authored
commit (#841)
1 parent 11011e6 commit 95a24a5

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package com.baeldung.combiningflows
2+
3+
import kotlinx.coroutines.delay
4+
import kotlinx.coroutines.flow.*
5+
import kotlinx.coroutines.runBlocking
6+
7+
// Sample Flow Creation
8+
suspend fun sampleFlow1(): Flow<Int> = flow {
9+
repeat(3) {
10+
delay(1000)
11+
emit(it)
12+
}
13+
}
14+
15+
suspend fun sampleFlow2(): Flow<Int> = flow {
16+
repeat(3) {
17+
delay(1500)
18+
emit(it * it)
19+
}
20+
}
21+
22+
// Method 1: zip
23+
suspend fun method1() {
24+
val combinedFlow = sampleFlow1().zip(sampleFlow2()) { first, second ->
25+
"($first, $second)"
26+
}
27+
combinedFlow.collect { println(it) }
28+
}
29+
30+
// Method 2: combine
31+
suspend fun method2() {
32+
val combinedFlow = sampleFlow1().combine(sampleFlow2()) { first, second ->
33+
"($first, $second)"
34+
}
35+
combinedFlow.collect { println(it) }
36+
}
37+
38+
// Method 3: flatMapConcat
39+
suspend fun method3() {
40+
val combinedFlow = sampleFlow1().flatMapConcat { value1 ->
41+
sampleFlow2().map { value2 ->
42+
"($value1, $value2)"
43+
}
44+
}
45+
combinedFlow.collect { println(it) }
46+
}
47+
48+
// Method 4: flatMapMerge
49+
suspend fun method4() {
50+
val combinedFlow = sampleFlow1().flatMapMerge { value1 ->
51+
sampleFlow2().map { value2 ->
52+
"($value1, $value2)"
53+
}
54+
}
55+
combinedFlow.collect { println(it) }
56+
}
57+
58+
// Method 5: flattenConcat
59+
suspend fun method5() {
60+
val combinedFlow = flowOf(sampleFlow1(), sampleFlow2()).flattenConcat()
61+
combinedFlow.collect { println(it) }
62+
}
63+
64+
// Method 6: merge
65+
suspend fun method6() {
66+
val combinedFlow = merge(sampleFlow1(), sampleFlow2())
67+
combinedFlow.collect { println(it) }
68+
}
69+
70+
fun main() = runBlocking {
71+
println("Method 1: zip")
72+
method1()
73+
74+
println("\nMethod 2: combine")
75+
method2()
76+
77+
println("\nMethod 3: flatMapConcat")
78+
method3()
79+
80+
println("\nMethod 4: flatMapMerge")
81+
method4()
82+
83+
println("\nMethod 5: flattenConcat")
84+
method5()
85+
86+
println("\nMethod 6: merge")
87+
method6()
88+
}

0 commit comments

Comments
 (0)