Skip to content

Instantly share code, notes, and snippets.

@AfzalivE
Last active February 4, 2021 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AfzalivE/3bfe168e879ba8b97ad62292217b0491 to your computer and use it in GitHub Desktop.
Save AfzalivE/3bfe168e879ba8b97ad62292217b0491 to your computer and use it in GitHub Desktop.
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