Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 677728d

Browse files
Code after 'sharedflows are hot' lecture
1 parent 26b5efa commit 677728d

File tree

2 files changed

+52
-7
lines changed

2 files changed

+52
-7
lines changed

‎app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/flow/hot_and_cold_flows/1-flows_are_cold.kt

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,34 @@ package com.lukaslechner.coroutineusecasesonandroid.playground.flow.hot_and_cold
33
import kotlinx.coroutines.coroutineScope
44
import kotlinx.coroutines.delay
55
import kotlinx.coroutines.flow.flow
6-
import kotlinx.coroutines.flow.onEach
6+
import kotlinx.coroutines.launch
77

88
fun coldFlow() = flow {
99
println("Emitting 1")
1010
emit(1)
1111

12+
delay(1000)
1213
println("Emitting 2")
1314
emit(2)
1415

16+
delay(1000)
1517
println("Emitting 3")
1618
emit(3)
17-
}.onEach {
18-
delay(1000)
1919
}
2020

2121
suspend fun main(): Unit = coroutineScope {
2222

23-
coldFlow()
24-
.collect {
25-
println("Collector 1 collects: $it")
26-
}
23+
launch {
24+
coldFlow()
25+
.collect {
26+
println("Collector 1 collects: $it")
27+
}
28+
}
29+
30+
launch {
31+
coldFlow()
32+
.collect {
33+
println("Collector 2 collects: $it")
34+
}
35+
}
2736
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.lukaslechner.coroutineusecasesonandroid.playground.flow.hot_and_cold_flows
2+
3+
import kotlinx.coroutines.CoroutineScope
4+
import kotlinx.coroutines.Dispatchers
5+
import kotlinx.coroutines.delay
6+
import kotlinx.coroutines.flow.MutableSharedFlow
7+
import kotlinx.coroutines.launch
8+
9+
fun main() {
10+
11+
val sharedFlow = MutableSharedFlow<Int>()
12+
13+
val scope = CoroutineScope(Dispatchers.Default)
14+
15+
scope.launch {
16+
repeat(5) {
17+
println("SharedFlow emits $it")
18+
sharedFlow.emit(it)
19+
delay(200)
20+
}
21+
}
22+
23+
scope.launch {
24+
sharedFlow.collect{
25+
println("Collected $it in collector 1")
26+
}
27+
}
28+
29+
scope.launch {
30+
sharedFlow.collect{
31+
println("Collected $it in collector 2")
32+
}
33+
}
34+
35+
Thread.sleep(1500)
36+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /