Skip to content

Instantly share code, notes, and snippets.

@chenzhang2006
Last active February 18, 2022 22:05
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 chenzhang2006/f6bbeb0fe965151555149f8dda2d6ed7 to your computer and use it in GitHub Desktop.
Save chenzhang2006/f6bbeb0fe965151555149f8dda2d6ed7 to your computer and use it in GitHub Desktop.
Prove CoroutineContext is inherited and overwritten by Coroutine child
fun CoroutineScope.logWithName(msg: String) { // log message with CoroutineName
val coroutineName = coroutineContext[CoroutineName]?.name
println("[$coroutineName] $msg")
}
fun main() = runBlocking(CoroutineName("main")) {
logWithName("Started") // [main] Started
launch {
delay(300)
logWithName("finished") // [main] finished
}
launch(CoroutineName("launch-101")) {
delay(500)
logWithName("finished") // [launch-101] finished
}
val value = async(CoroutineName("async-202")) {
delay(1000)
logWithName("finished") // [async-202] finished
888
}
logWithName("Got ${value.await()}") // [main] Got 888
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment