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 (" \n Method 2: combine" )
75
+ method2()
76
+
77
+ println (" \n Method 3: flatMapConcat" )
78
+ method3()
79
+
80
+ println (" \n Method 4: flatMapMerge" )
81
+ method4()
82
+
83
+ println (" \n Method 5: flattenConcat" )
84
+ method5()
85
+
86
+ println (" \n Method 6: merge" )
87
+ method6()
88
+ }
0 commit comments