0
0
Kotlinprogramming~30 mins

SupervisorJob for independent failure in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
SupervisorJob for independent failure
📖 Scenario: You are building a Kotlin program that launches two independent tasks using coroutines. You want to make sure that if one task fails, the other task continues running without being cancelled.
🎯 Goal: Create a Kotlin program that uses SupervisorJob to launch two coroutines. One coroutine will throw an exception, and the other will complete successfully. The program should show that the failure of one coroutine does not cancel the other.
📋 What You'll Learn
Create a SupervisorJob instance called supervisor
Create a CoroutineScope called scope using supervisor
Launch two coroutines inside scope named job1 and job2
job1 should throw an exception after a short delay
job2 should print a success message after a longer delay
Use join() to wait for both coroutines to finish
Print messages to show the independent failure behavior
💡 Why This Matters
🌍 Real World
In real apps, you often want some tasks to continue even if others fail, like loading multiple independent data sources.
💼 Career
Understanding <code>SupervisorJob</code> is important for Kotlin developers working with coroutines to build resilient and fault-tolerant applications.
Progress0 / 4 steps
1
Create a SupervisorJob and CoroutineScope
Create a val supervisor and set it to SupervisorJob(). Then create a val scope and set it to CoroutineScope(supervisor + Dispatchers.Default).
Kotlin
Need a hint?

Use SupervisorJob() to create the supervisor job. Combine it with Dispatchers.Default to create the scope.

2
Launch two coroutines with independent behavior
Inside scope, launch two coroutines called job1 and job2. In job1, delay 100 ms then throw an exception with throw RuntimeException("Failure in job1"). In job2, delay 300 ms then print "Job2 completed successfully".
Kotlin
Need a hint?

Use scope.launch { ... } to start each coroutine. Use delay() to wait before throwing or printing.

3
Wait for both coroutines to finish
Use job1.join() and job2.join() to wait for both coroutines to complete.
Kotlin
Need a hint?

Use runBlocking { ... } to wait for the coroutines. Use try-catch around job1.join() to catch the exception.

4
Print final message showing independent failure
After waiting for both jobs, print "Program completed: job1 failed but job2 succeeded" to show that the failure of job1 did not cancel job2.
Kotlin
Need a hint?

Use println() to print the final message after both jobs finish.