Last active
February 4, 2021 17:58
-
-
Save AfzalivE/3bfe168e879ba8b97ad62292217b0491 to your computer and use it in GitHub Desktop.
Coroutines cancellation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main(args: Array<String>) { | |
val handler = CoroutineExceptionHandler { context, exception -> | |
println("CoroutineExceptionHandler got $exception with suppressed ${exception.suppressed.contentToString()}") | |
} | |
val parentScope = CoroutineScope(Dispatchers.Default + Job() + handler) | |
// val parentScope = MyScope() | |
parentScope.launch { | |
println("one job: " + this.coroutineContext[Job].toString()) | |
println("Hello") | |
delay(800) | |
// try { | |
throw NullPointerException("faiiiil") | |
// } catch (e: Exception) { | |
// cancel("cancelled 1") | |
// } | |
println("World") | |
} | |
parentScope.launch { | |
delay(1500) | |
this.coroutineContext.ensureActive() | |
println("Sibling job") | |
} | |
val input = readLine() | |
println("Your input was $input") | |
parentScope.launch { | |
println("third job") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyScope: CoroutineScope { | |
private val handler = CoroutineExceptionHandler { context, exception -> | |
println("CoroutineExceptionHandler got $exception with suppressed ${exception.suppressed.contentToString()}") | |
} | |
override val coroutineContext: CoroutineContext | |
get() = Dispatchers.Default + Job() + handler | |
fun run() { | |
launch { | |
println("one job: " + this.coroutineContext[Job].toString()) | |
println("Hello") | |
delay(800) | |
// try { | |
throw NullPointerException("faiiiil") | |
// } catch (e: Exception) { | |
// cancel("cancelled 1") | |
// } | |
println("World") | |
} | |
launch { | |
delay(1500) | |
this.coroutineContext.ensureActive() | |
println("Sibling job") | |
} | |
val input = readLine() | |
println("Your input was $input") | |
launch { | |
println("third job") | |
} | |
} | |
} | |
fun main(args: Array<String>) { | |
MyScope().run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment