fun main() = runBlocking {
val job = launch {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
}
delay(1300L) // delay a bit
println("main: I'm tired of waiting!")
job.cancel() // cancels the job
job.join() // waits for job's completion
println("main: Now I can quit.")
}
How does Kotlin stop execution of
launch
code block?
l
louiscad
08/27/2019, 12:05 PM
A
CancellationException
is thrown.
k
kalpeshp0310
08/27/2019, 12:18 PM
Thanks Louis 🙂
kalpeshp0310
08/27/2019, 12:24 PM
Is there a way to know that launch is canceled from inside?
l
louiscad
08/27/2019, 12:42 PM
You can check
isActive
while catching
CancellationException
, but do you really need to do so?
👍 1
k
kalpeshp0310
08/27/2019, 1:02 PM
No, I was just trying to understand how exception flows and how coroutine cancels job.