Skip to content

Commit a8d3dd6

Browse files
flows-merge (#858)
* commit * commit * commit * update * update * remove the comment * Update core-kotlin-modules/core-kotlin-concurrency-3/src/test/java/com/baeldung/mergemultipleflows/MergeFlowsUnitTest.kt Co-authored-by: Brandon Ward <[email protected]> --------- Co-authored-by: Brandon Ward <[email protected]>
1 parent c2b81e9 commit a8d3dd6

File tree

1 file changed

+75
-0
lines changed
  • core-kotlin-modules/core-kotlin-concurrency-3/src/test/java/com/baeldung/mergemultipleflows

1 file changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.baeldung.mergemultipleflows
2+
3+
import kotlinx.coroutines.*
4+
import kotlinx.coroutines.flow.*
5+
import org.assertj.core.api.Assertions.assertThat
6+
import org.junit.jupiter.api.Test
7+
import kotlin.test.assertEquals
8+
9+
class FlowMergingTests {
10+
11+
@Test
12+
fun `should merge using the merge function`(): Unit = runBlocking {
13+
val flow1 = flowOf(1, 2, 3, 4)
14+
val flow2 = flowOf(5, 6, 7, 8)
15+
val mergedFlow = merge(flow1, flow2)
16+
val result = mergedFlow.toList()
17+
18+
assertThat(result).containsExactlyInAnyOrder(1, 2, 3, 4, 5, 6, 7, 8)
19+
}
20+
21+
@Test
22+
fun `should merge using zip`() = runBlocking {
23+
val flow1 = flowOf(1, 2, 3)
24+
val flow2 = flowOf("A", "B", "C")
25+
26+
val result = flow1.zip(flow2) { num, letter ->
27+
"$num$letter"
28+
}.toList()
29+
30+
assertEquals(listOf("1A", "2B", "3C"), result)
31+
}
32+
33+
34+
@Test
35+
fun `should merge using combine`() = runBlocking {
36+
val flow1 = flowOf(0)
37+
val flow2 = flowOf(1, 2, 3)
38+
val result = flow1.combine(flow2) { num1, num2 ->
39+
num1 + num2
40+
}.toList()
41+
assertEquals(listOf(1, 2, 3), result)
42+
}
43+
44+
45+
46+
@Test
47+
fun `should merge using flatmapconcat`() = runBlocking {
48+
val flow1 = flowOf(1, 2, 3)
49+
val flow2 = flowOf(4, 5, 6)
50+
val result = flow1.flatMapConcat { value1 ->
51+
flow2.map { value2 -> value1 + value2 }
52+
}.toList()
53+
assertEquals(listOf(5, 6, 7, 6, 7, 8, 7, 8, 9), result)
54+
}
55+
56+
57+
@Test
58+
fun `should merge using flatmapmerge`() = runBlocking {
59+
val flow1 = flowOf(1, 2, 3)
60+
val flow2 = flowOf(4, 5, 6)
61+
val result = flow1.flatMapMerge { value1 ->
62+
flow2.map { value2 -> value1 + value2 }
63+
}.toList()
64+
assertEquals(listOf(5, 6, 7, 6, 7, 8, 7, 8, 9), result)
65+
}
66+
67+
68+
@Test
69+
fun `should merge using runningReduce`() = runBlocking {
70+
val result = flowOf(1, 2, 3, 4)
71+
.runningReduce { acc, value -> acc + value }
72+
.toList()
73+
assertEquals(listOf(1, 3, 6, 10), result)
74+
}
75+
}

0 commit comments

Comments
 (0)