Skip to Content
Course content

227: Debugging Kotlin Coroutines with the Debugger

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this happen to a lot of developers moving from standard synchronous code to coroutines: you set a breakpoint, you hit "Run", and suddenly your debugger feels like it's lying to you. You click "Step Over," and instead of going to the next line, the debugger jumps to some internal Kotlin library code, or worse, the execution just... stops. You're staring at a UI spinner that never disappears, but you have no idea which coroutine is stuck or why.

Take a look at this snippet. We're trying to fetch a user profile and their recent posts in parallel, then combine them. It looks clean, but in a real-world scenario, if the fetchPosts call hangs due to a network timeout that isn't properly configured, the whole dashboard just freezes.

suspend fun loadDashboardData() = coroutineScope {
    val profileDeferred = async { api.fetchProfile() }
    val postsDeferred = async { api.fetchPosts() } // This one hangs indefinitely

    val profile = profileDeferred.await()
    val posts = postsDeferred.await() // Debugger stops here... and stays here
    
    updateUI(profile, posts)
}

The "Ghost" Suspension Problem

If you try to debug this using only the standard "Frames" window, you'll see the current thread is idling. That's because the thread has been released back to the dispatcher while the coroutine is suspended. You aren't "stuck" on a line of code in the way you are with a while(true) loop; you're suspended in a state machine.

When I hit this wall, I stop looking at the Threads tab and switch to the Coroutines tab in the IntelliJ/Android Studio debugger. If you don't see it, make sure you're running in debug mode and look for the "Coroutines" panel next to the "Variables" and "Frames" views.

When you look at that tab during the hang, you'll see a list of all active coroutines. You'll likely see one marked as SUSPENDED. By clicking on it, the debugger will take you exactly to the line where that specific coroutine is waiting—even if that coroutine is currently distributed across three different threads over its lifetime. I've found this is the only way to distinguish between a deadlock and a simple slow network call.

Exposing the Hang with Debugger Settings

Sometimes the Coroutines tab tells you where it's stuck, but not why. If you're dealing with a complex chain of async and await calls, it can be hard to track which child coroutine is the culprit.

I highly recommend enabling "Coroutine Debugger" in your JVM options if you're doing heavy development. By adding -Dkotlinx.coroutines.debug to your VM options, Kotlin adds the coroutine name and creation stack trace to the debugger. Suddenly, instead of seeing coroutine #2, you see coroutine #2 @DashboardViewModel.kt:42.

In our broken code above, the fix is twofold: adding a withTimeout block to prevent infinite suspension and using a SupervisorJob or try-catch within the async block so one failure doesn't silently kill the entire scope. Here is how I'd refactor it to be "debug-friendly" and resilient:

suspend fun loadDashboardData() = coroutineScope {
    val profileDeferred = async { 
        api.fetchProfile() 
    }
    val postsDeferred = async { 
        withTimeout(5000L) { // Now the debugger will show a TimeoutCancellationException
            api.fetchPosts() 
        }
    }

    try {
        val profile = profileDeferred.await()
        val posts = postsDeferred.await()
        updateUI(profile, posts)
    } catch (e: Exception) {
        showErrorState(e)
    }
}

Now, if the posts call hangs, the debugger won't just show a suspended coroutine forever. After five seconds, you'll see the exception trigger, the stack trace will point you directly to the withTimeout block, and you can actually see the flow move into the catch block. It turns a "mystery hang" into a predictable event.




📋 Practical Task

Debug the Hanging Order Processor

You are working on an e-commerce app. The processOrder function is supposed to validate the payment and update the inventory simultaneously. However, users are reporting that the "Processing Order" screen stays up forever.

Your Task:

  1. Copy the following code into your IDE.
  2. Run it in Debug Mode.
  3. Use the Coroutines Tab to identify which specific async block is causing the suspension.
  4. Implement a withTimeout wrapper around the hanging call to ensure the app recovers and calls handleFailure() instead of hanging indefinitely.
import kotlinx.coroutines.*

class OrderService {
    suspend fun validatePayment(): Boolean {
        delay(500)
        return true
    }

    suspend fun updateInventory() {
        // SIMULATED BUG: This call hangs indefinitely
        delay(Long.MAX_VALUE) 
    }
}

suspend fun processOrder() = coroutineScope {
    val service = OrderService()
    
    val payment = async { service.validatePayment() }
    val inventory = async { service.updateInventory() }

    try {
        if (payment.await() && inventory.await()) {
            println("Order Successful!")
        }
    } catch (e: Exception) {
        handleFailure(e)
    }
}

fun handleFailure(e: Exception) {
    println("Order failed due to: ${e.message}")
}

fun main() = runBlocking {
    processOrder()
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.