Last active
July 22, 2021 01:34
-
-
Save lgtout/420def74f57464c5716b3835c01d7953 to your computer and use it in GitHub Desktop.
withContext 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
import kotlinx.coroutines.* | |
import java.util.concurrent.ThreadLocalRandom | |
fun main() { | |
val job = GlobalScope.launch { | |
Thread.sleep(1000) | |
try { | |
println(1) | |
withContext(CoroutineName("foo")) { | |
val rnd = ThreadLocalRandom.current() | |
val sum = (1..100_000_000).sumOf { rnd.nextInt() } | |
println("Same dispatcher sum = $sum") | |
} | |
} catch (e: Exception) { | |
println("Same dispatcher threw: $e") | |
throw e | |
} | |
try { | |
withContext(Dispatchers.IO) { | |
val rnd = ThreadLocalRandom.current() | |
val sum = (1..100_000_000).sumOf { rnd.nextInt() } | |
println("Changed dispatcher sum = $sum") | |
} | |
} catch (e: Exception) { | |
println("Changed dispatcher threw: $e") | |
throw e | |
} | |
} | |
job.invokeOnCompletion { cause -> println("job completed with $cause") } | |
job.cancel() | |
Thread.currentThread().join() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: