Skip to content

Supervisor Scope and Supervisor Job in coroutines

Devrath edited this page Feb 27, 2024 · 1 revision

In Kotlin's coroutine framework for Android, a supervisor is a coroutine scope builder, and a supervisor job is a specific type of job associated with a supervisor scope. Let's break down the difference between the two:

  1. Supervisor Scope:

    • A supervisor scope is a coroutine scope builder provided by Kotlin's coroutine library. It is created using the supervisorScope function.
    • When a coroutine within a supervisor's scope encounters a failure (an exception), it doesn't cancel the rest of the coroutines within the scope. Instead, the failure is propagated up to the supervisor's scope, and the other coroutines continue to execute.
    • The supervisorScope is typically used when you want to isolate failures in a specific coroutine and prevent them from affecting the entire scope.

    Example:

    suspend fun performTask() {
        supervisorScope {
            launch {
                // Coroutine 1
                // ...
            }
            launch {
                // Coroutine 2
                // ...
            }
        }
    }
  2. Supervisor Job:

    • A supervisor job is a specific type of job that is associated with a supervisor scope. When you launch a coroutine within a supervisor scope, it returns a Job object, and this job is a supervisor job.
    • The supervisor job is responsible for tracking the coroutines launched within the supervisor's scope and handling their completion or failure in a way that doesn't affect the other coroutines within the scope.
    • You can use the CoroutineExceptionHandler to handle exceptions within the supervisor job.

    Example:

    val supervisorJob = SupervisorJob()
    
    val coroutineExceptionHandler = CoroutineExceptionHandler { _, exception ->
        // Handle exception
        println("Coroutine failed: $exception")
    }
    
    val coroutineScope = CoroutineScope(Dispatchers.Main + supervisorJob + coroutineExceptionHandler)
    
    coroutineScope.launch {
        // Coroutine 1
        // ...
    }
    
    coroutineScope.launch {
        // Coroutine 2
        // ...
    }

In summary, a supervisor scope is a way to structure coroutines to isolate failures, and a supervisor job is a job associated with that scope, responsible for managing the execution and failures of the coroutines within the scope.

Clone this wiki locally