Skip to content

Commit e83a6ca

Browse files
Add playground examples for structured concurrency
1 parent 1ca0b45 commit e83a6ca

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.lukaslechner.coroutineusecasesonandroid.playground.structuredconcurrency
2+
3+
import kotlinx.coroutines.*
4+
5+
fun main() {
6+
7+
val exceptionHandler = CoroutineExceptionHandler { context, exception ->
8+
println("Caught exception $exception")
9+
}
10+
11+
val scope = CoroutineScope(SupervisorJob() + exceptionHandler)
12+
13+
scope.launch {
14+
println("Coroutine 1 starts")
15+
delay(50)
16+
println("Coroutine 1 fails")
17+
throw RuntimeException()
18+
}
19+
20+
scope.launch {
21+
println("Coroutine 2 starts")
22+
delay(500)
23+
println("Coroutine 2 completed")
24+
}.invokeOnCompletion { throwable ->
25+
if (throwable is CancellationException) {
26+
println("Coroutine 2 got cancelled!")
27+
}
28+
}
29+
30+
Thread.sleep(1000)
31+
32+
println("Scope got cancelled: ${!scope.isActive}")
33+
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.lukaslechner.coroutineusecasesonandroid.playground.structuredconcurrency
2+
3+
import kotlinx.coroutines.*
4+
5+
fun main() {
6+
7+
val scope = CoroutineScope(Job())
8+
9+
scope.launch {
10+
11+
doSomeTasks()
12+
13+
launch {
14+
println("Starting Task 3")
15+
delay(300)
16+
println("Task 3 completed")
17+
}
18+
}
19+
20+
Thread.sleep(1000)
21+
}
22+
23+
suspend fun doSomeTasks() = coroutineScope {
24+
launch {
25+
println("Starting Task 1")
26+
delay(100)
27+
println("Task 1 completed")
28+
}
29+
30+
launch {
31+
println("Starting Task 2")
32+
delay(200)
33+
println("Task 2 completed")
34+
}
35+
}

0 commit comments

Comments
 (0)