Skip to content

Commit 56f0375

Browse files
Add playground files for buffers in SharedFlows and StateFlows
1 parent 9ece193 commit 56f0375

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.lukaslechner.coroutineusecasesonandroid.playground.flow.concurrency
2+
3+
import kotlinx.coroutines.coroutineScope
4+
import kotlinx.coroutines.delay
5+
import kotlinx.coroutines.flow.MutableStateFlow
6+
import kotlinx.coroutines.launch
7+
import kotlin.system.measureTimeMillis
8+
9+
suspend fun main(): Unit = coroutineScope {
10+
11+
val flow = MutableStateFlow(0)
12+
13+
// Collector 1
14+
launch {
15+
flow.collect {
16+
println("Collector 1 processes $it")
17+
}
18+
}
19+
20+
// Collector 2
21+
launch {
22+
flow.collect {
23+
println("Collector 2 processes $it")
24+
delay(100)
25+
}
26+
}
27+
28+
// Emitter
29+
launch {
30+
val timeToEmit = measureTimeMillis {
31+
repeat(5) {
32+
flow.emit(it)
33+
delay(10)
34+
}
35+
}
36+
println("Time to emit all values: $timeToEmit ms")
37+
}
38+
}

app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/flow/concurrency/9_buffer_in_sharedflow.kt

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import kotlin.system.measureTimeMillis
88

99
suspend fun main(): Unit = coroutineScope {
1010

11-
val flow = MutableSharedFlow<Int>()
11+
val flow = MutableSharedFlow<Int>(extraBufferCapacity = 10)
1212

1313
// Collector 1
1414
launch {
@@ -17,6 +17,14 @@ suspend fun main(): Unit = coroutineScope {
1717
}
1818
}
1919

20+
// Collector 2
21+
launch {
22+
flow.collect {
23+
println("Collector 2 processes $it")
24+
delay(100)
25+
}
26+
}
27+
2028
// Emitter
2129
launch {
2230
val timeToEmit = measureTimeMillis {

0 commit comments

Comments
 (0)