article banner

Exercise: Understanding context propagation

Fill the gaps in the following code. Both the log and slog functions should print the name of the coroutine they are called from, and message from argument.

suspend fun log(msg: String) { val name = ___[CoroutineName]?.name println("[$name] $msg") } fun CoroutineScope.slog(msg: String) { val name = ___[CoroutineName]?.name println("[$name] $msg") } suspend fun main(): Unit = withContext(CoroutineName("Outer")) { log("Starting") // [___] Starting launch(CoroutineName("Inner")) { slog("A") // [___] A launch { log("B") // [___] B } } launch { slog("C") // [___] C } GlobalScope.launch { log("D") // [___] D } slog("Ending") // [___] Ending }

Once you are done with the exercise, you can check your solution here.