-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
FlatMapMergeTest.kt
116 lines (101 loc) · 2.84 KB
/
FlatMapMergeTest.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlin.test.*
class FlatMapMergeTest : FlatMapMergeBaseTest() {
override fun <T> Flow<T>.flatMap(mapper: suspend (T) -> Flow<T>): Flow<T> = flatMapMerge(transform = mapper)
@Test
override fun testFlatMapConcurrency() = runTest {
var concurrentRequests = 0
val flow = (1..100).asFlow().flatMapMerge(concurrency = 2) { value ->
flow {
++concurrentRequests
emit(value)
delay(Long.MAX_VALUE)
}
}
val consumer = launch {
flow.collect { value ->
expect(value)
}
}
repeat(4) {
yield()
}
assertEquals(2, concurrentRequests)
consumer.cancelAndJoin()
finish(3)
}
@Test
fun testAtomicStart() = runTest {
try {
coroutineScope {
val job = coroutineContext[Job]!!
val flow = flow {
expect(3)
emit(1)
}
.onCompletion { expect(5) }
.flatMapMerge {
expect(4)
flowOf(it).onCompletion { expectUnreached() } }
.onCompletion { expect(6) }
launch {
expect(1)
flow.collect()
}
launch {
expect(2)
yield()
job.cancel()
}
}
} catch (e: CancellationException) {
finish(7)
}
}
@Test
fun testCancellationExceptionDownstream() = runTest {
val flow = flowOf(1, 2, 3).flatMapMerge {
flow {
emit(it)
throw CancellationException("")
}
}
assertEquals(listOf(1, 2, 3), flow.toList())
}
@Test
fun testCancellationExceptionUpstream() = runTest {
val flow = flow {
expect(1)
emit(1)
expect(2)
yield()
throw CancellationException("")
}.flatMapMerge {
flow {
expect(3)
emit(it)
hang { expect(4) }
}
}
assertFailsWith<CancellationException>(flow)
finish(5)
}
@Test
fun testCancellation() = runTest {
val result = flow {
emit(1)
emit(2)
emit(3)
emit(4)
expectUnreached() // Cancelled by take
emit(5)
}.flatMapMerge(2) { v -> flow { emit(v) } }
.take(2)
.toList()
assertEquals(listOf(1, 2), result)
}
}