Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
227: Debugging Kotlin Coroutines with the Debugger
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:
- Copy the following code into your IDE.
- Run it in Debug Mode.
- Use the Coroutines Tab to identify which specific
asyncblock is causing the suspension. - Implement a
withTimeoutwrapper around the hanging call to ensure the app recovers and callshandleFailure()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()
}There are no comments for now.