Coroutine Exception Handling — supervisorScope & CoroutineExceptionHandler
Coroutines require careful exception handling. A failure in one child can cancel siblings. Use supervisorScope to isolate failures and CoroutineExceptionHandler for global handling.
supervisorScope Pattern
viewModelScope.launch {
supervisorScope {
val task1 = async { fetchData1() }
val task2 = async { fetchData2() }
task1.await() // failure doesn't cancel task2
task2.await()
}
}
Global Exception Handler
val handler = CoroutineExceptionHandler { _, exception ->
Log.e("Coroutine", "Caught: ${exception.message}")
showErrorUI(exception)
}
viewModelScope.launch(handler) {
riskyOperation()
}
Best Practice
Use supervisorScope for independent tasks and CoroutineExceptionHandler for UI notifications.
8 production-ready Android app templates on Gumroad.
Browse templates → Gumroad
Top comments (0)