Describe a scenario where using `supervisorScope` is crucial and explain why a simple `coroutineScope` would be insufficient. Illustrate with a Kotlin code example.

Android interview question for Advanced practice.

Answer

A scenario where supervisorScope is crucial is when you have multiple independent child coroutines, and the failure of one should not cause the others to cancel. For instance, in a system monitoring application, you might launch separate coroutines to monitor different services (CPU, memory, network). If one service fails, the monitoring of the others should continue. Using coroutineScope would cause the entire scope to cancel, halting all monitoring. kotlin import kotlinx.coroutines. suspend fun monitorServices() = supervisorScope { launch { monitorCPU() } launch { monitorMemory() } launch { monitorNetwork() } } suspend fun monitorCPU() = withContext(Dispatchers.IO) { delay(1000) throw Exception("CPU Failure!") } suspend fun monitorMemory() = withContext(Dispatchers.IO) { delay(2000) println("Memory OK") } suspend fun monitorNetwork() = withContext(Dispatchers.IO) { delay(3000) println("Network OK") } fun main() = runBlocking { try { monitorServices() } catch (e: Exception) { println("Exception caught: ${e.message}") } } With supervisorScope, even if monitorCPU() throws an exception, monitorMemory() and monitorNetwork() will continue to execute.

Explanation

The supervisorScope builder is particularly useful when dealing with error handling in concurrent operations, as it prevents the entire scope from failing due to a single child coroutine exception.

Related Questions