Skip to Content
Course content

101: SupervisorJob and Exception Propagation

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

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 Job with a mechanism that prevents sibling cancellation.
  • Ensure the logic is contained within the downloadGalleryImages function.
  • Test your logic mentally: if urls[1] fails, do urls[0] and urls[2] still complete?
Rating
0 0

There are no comments for now.

to be the first to leave a comment.