-
Notifications
You must be signed in to change notification settings - Fork 1
/
LosingLastBatch.kt
73 lines (59 loc) · 1.77 KB
/
LosingLastBatch.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
package org.kollektions.examples.extending
import org.kollektions.consumers.Consumer
import org.kollektions.consumers.consume
import kotlin.test.Test
class LosingLastBatch {
@Test
fun `BatchSaverV1 does not implement stop and loses last batch`() {
(1..5).asSequence().consume(BatchSaverV1(3))
}
/*
Output:
Saving batch [1, 2, 3]
*/
@Test
fun `BatchSaverV2 implements stop and saves last batch`() {
(1..5).asSequence().consume(BatchSaverV2(3))
}
/*
Output:
Saving batch [1, 2, 3]
Saving batch [4, 5]
*/
private class BatchSaverV1(val batchSize: Int): Consumer<Int> {
private val buffer = mutableListOf<Int>()
private val database = FakeDatabase()
override fun process(value: Int) {
buffer.add(value)
if(buffer.size == batchSize) {
println("Saving buffer from process()")
database.save(buffer)
buffer.clear()
}
}
override fun results(): Any = 42
override fun stop() {}
}
private class BatchSaverV2(val batchSize: Int): Consumer<Int> {
private val buffer = mutableListOf<Int>()
private val database = FakeDatabase()
override fun process(value: Int) {
buffer.add(value)
if(buffer.size == batchSize) {
println("Saving buffer from process()")
database.save(buffer)
buffer.clear()
}
}
override fun results(): Any = 42
override fun stop() {
println("Saving buffer from stop()")
database.save(buffer)
}
}
private class FakeDatabase {
fun save(batch: List<Int>) {
println("Saving batch $batch")
}
}
}