File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/cancellation Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ package com.lukaslechner.coroutineusecasesonandroid.playground.cancellation
2+
3+ import kotlinx.coroutines.CancellationException
4+ import kotlinx.coroutines.delay
5+ import kotlinx.coroutines.launch
6+ import kotlinx.coroutines.runBlocking
7+
8+ fun main () = runBlocking {
9+
10+ val job = launch {
11+ repeat(10 ) { index ->
12+ println (" operation number $index " )
13+ try {
14+ delay(100 )
15+ } catch (exception: CancellationException ) {
16+ println (" CancellationException was thrown" )
17+ throw CancellationException ()
18+ }
19+ }
20+ }
21+
22+ delay(250 )
23+ println (" Cancelling Coroutine" )
24+ job.cancel()
25+ }
Original file line number Diff line number Diff line change 1+ package com.lukaslechner.coroutineusecasesonandroid.playground.cancellation
2+
3+ import kotlinx.coroutines.*
4+
5+ fun main () = runBlocking<Unit > {
6+
7+ val job = launch(Dispatchers .Default ) {
8+ repeat(10 ) { index ->
9+ if (isActive) {
10+ println (" operation number $index " )
11+ Thread .sleep(100 )
12+ } else {
13+ // perform some cleanup on cancellation
14+ withContext(NonCancellable ) {
15+ delay(100 )
16+ println (" Clean up done!" )
17+ }
18+ throw CancellationException ()
19+ }
20+ }
21+ }
22+
23+ delay(250 )
24+ println (" Cancelling Coroutine" )
25+ job.cancel()
26+
27+ val globalCoroutineJob = GlobalScope .launch {
28+ repeat(10 ) {
29+ println (" $it " )
30+ delay(100 )
31+ }
32+ }
33+ delay(250 )
34+ globalCoroutineJob.cancel()
35+ delay(1000 )
36+ }
You can’t perform that action at this time.
0 commit comments