Skip to content

Commit 9117613

Browse files
[KTLN-773] Get Current and Previous Value in Kotlin Flow's collect (#1123)
* redone code * code changes * code changes
1 parent f1ef5d5 commit 9117613

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.firstAndPrevFlowValue
2+
3+
import junit.framework.TestCase.assertEquals
4+
import kotlinx.coroutines.flow.*
5+
import kotlinx.coroutines.test.runTest
6+
import org.junit.jupiter.api.Test
7+
8+
class FirstAndPrevFlowValueUnitTest {
9+
@Test
10+
fun `test manually tracking previous and current value`() = runTest {
11+
val flow = flowOf(1, 2, 3, 4, 5)
12+
var previousValue: Int? = null
13+
val results = mutableListOf<Pair<Int?, Int>>()
14+
15+
flow.collect { currentValue ->
16+
results.add(Pair(previousValue, currentValue))
17+
previousValue = currentValue
18+
}
19+
20+
assertEquals(listOf(Pair(null, 1), Pair(1, 2), Pair(2, 3), Pair(3, 4), Pair(4, 5)), results)
21+
}
22+
23+
@Test
24+
fun `test runningFold for previous and current value`() = runTest {
25+
val flow = flowOf(1, 2, 3, 4, 5)
26+
val initial: Pair<Int?, Int?> = null to null
27+
val results = mutableListOf<Pair<Int?, Int?>>()
28+
29+
flow.runningFold(initial) { lastPair, next ->
30+
lastPair.run {
31+
val (_, last) = this
32+
last to next
33+
}
34+
}
35+
.collect { results.add(it) }
36+
37+
assertEquals(listOf(Pair(null, null), Pair(null, 1), Pair(1, 2), Pair(2, 3), Pair(3, 4), Pair(4, 5)), results)
38+
}
39+
}

0 commit comments

Comments
 (0)