Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Coroutines cancellation
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")
}
}
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