Search⌘ K
AI Features

Debugging Coroutines

Explore how to debug Kotlin coroutines by using the -Dkotlinx.coroutines.debug option to see coroutine details during execution. Discover how to assign meaningful names to coroutines for easier tracking and understand the concurrency behavior of functions like withContext and launch in Kotlin. This lesson helps you gain practical skills to identify and troubleshoot coroutine execution contexts effectively.

“Prefer testing over debugging” is a good mantra to follow, but occasionally we have to debug code. Even when we follow good test-driven development practices, we’ll have to dig into the execution to look at why things aren’t working the way we expect. We’ll look at testing coroutines in Chapter 19, Unit Testing with Kotlin, but for now let’s figure out a way to find out which coroutines are running our code.

Running in debug mode

Kotlin provides a command-line option -Dkotlinx.coroutines.debug to display the details of the coroutine executing a function. When you print the details of a thread, the coroutine that’s running in that thread is displayed. Let’s use that option on the previous code.

 ...