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
101: SupervisorJob and Exception Propagation
I've seen this exact bug crop up in dozens of code reviews. You're building a dashboard, and you want to fire off a few independent requests—maybe one for the user's profile, one for their recent notifications, and one for their account balance. You think, "I'll just launch these in a scope, and if one fails, the others will still finish."
But when you actually run the code, you notice something weird: as soon as the notifications request hits a 404 or a timeout, the profile and balance requests just... stop. They vanish. No error message for those two, they just get cancelled.
suspend fun loadDashboard() {
val scope = CoroutineScope(Job() + Dispatchers.Main)
scope.launch {
fetchUserProfile() // This works fine
println("Profile loaded")
}
scope.launch {
throw IllegalStateException("Notifications service is down!") // Boom.
}
scope.launch {
fetchAccountBalance() // This never finishes
println("Balance loaded")
}
}
The Domino Effect of a Single Failure
Here is what's happening under the hood. In Kotlin, the default Job is designed for structured concurrency. This sounds great in a manual, but in practice, it means "all for one and one for all."
When a child coroutine fails with an exception, it doesn't just die quietly. It tells its parent, "I've failed!" The parent then does two things: it cancels all its other children and then fails itself. In the code above, when the Notifications coroutine throws that IllegalStateException, it triggers a chain reaction. The parent Job catches the failure, immediately kills the Profile and Balance coroutines, and shuts down the entire scope.
I've always found this frustrating when I'm dealing with independent tasks. Why should a broken notification bell prevent a user from seeing their account balance?
Isolating Failures with SupervisorJob
To stop this domino effect, we need a SupervisorJob. A supervisor job changes the rules: a failure in one child does not result in the cancellation of the other children, nor does it kill the parent.
suspend fun loadDashboard() {
// We swap Job() for SupervisorJob()
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
scope.launch {
fetchUserProfile()
println("Profile loaded")
}
scope.launch {
throw IllegalStateException("Notifications service is down!")
}
scope.launch {
fetchAccountBalance()
println("Balance loaded")
}
}
Now, when the notification coroutine crashes, the SupervisorJob simply acknowledges it. It doesn't panic. It lets the Profile and Balance coroutines keep humming along. This is exactly what you want for independent UI components.
The Trap: Where You Place the Supervisor
Here is the part where most developers get tripped up. You might try to put a SupervisorJob inside a launch block, thinking you're protecting that specific area. It won't work.
A SupervisorJob only works if it is the direct parent of the coroutines you want to isolate. If you have a regular Job at the top level and a SupervisorJob nested deeper, the regular Job will still see the exception propagate up and cancel everything anyway.
If you don't want to create a whole new scope, use supervisorScope { ... }. This is a scoping function that creates a temporary supervisor context for everything inside its block. It's usually the cleaner way to handle this in a suspend function without leaking memory by creating manual CoroutineScope instances.
📋 Practical Task
Fixing the Multi-Image Downloader
You are building a gallery app that downloads five images simultaneously. Currently, if a single image URL is broken and throws an exception, the entire download process halts, and none of the other images are saved to the disk.
Your Goal: Modify the following code so that if one image fails to download, the other four continue to download and save successfully.
suspend fun downloadGalleryImages(urls: List) {
val scope = CoroutineScope(Job() + Dispatchers.IO)
urls.forEach { url ->
scope.launch {
downloadImage(url) // This throws an IOException if the URL is 404
println("Successfully downloaded $url")
}
}
}
Requirements:
- Replace the standard
Jobwith a mechanism that prevents sibling cancellation. - Ensure the logic is contained within the
downloadGalleryImagesfunction. - Test your logic mentally: if
urls[1]fails, dourls[0]andurls[2]still complete?
There are no comments for now.