Coroutine scope vs Supervisor scope
In this blog we will learn about the difference between Coroutine scope and supervisor scope. This will be short read as the differences are pretty straight forward.
So, let’s get started.
The major difference between the 2 scopes is that coroutine scope will cancel the scope and all of it’s work, if there is any error within the scope.
Supervisor scope will continue to complete the tasks within the scope if there is an individual try-catch.
Let’s look at it with help of an example to understand better.
Example —
Assume that we have 2 network calls within scope that must be run in parallel.
launch {
try {
val networkCall1 = async { getData() }
val networkCall2 = async { getMoreData() }
val resultData = networkCall1.await()
val resultMoreData = networkCall2.await()
} catch (e: Exception) {
}
}
In this example, If there is any error while performing network operations the APP will CRASH.
To handle this use coroutineScope.
launch {
coroutineScope {
try {
val networkCall1 = async { getData() }
val networkCall2 = async { getMoreData() }
val resultData = networkCall1.await()
val resultMoreData = networkCall2.await()
} catch (e: Exception) {
//handle exception
}
}
}
This, solves only one part of the problem. If there is any error then it is propagated to catch block. But, the whole scope is cancelled which leads to un-necessary extra calls.
To handle this use supervisor-scope with individual try-catch block’s so that, If one network call fails only that call is affected.
launch {
supervisorScope {
val networkCall1 = async { getData() }
val networkCall2 = async { getMoreData() }
val resultData = try {
networkCall1.await()
} catch (e: Exception) {
//exception in first call
}
val resultMoreData = try {
networkCall2.await()
} catch (e: Exception) {
//exception in second call
}
}
}
Conclusion —
Use coroutineScope if you want the scope to be cancelled immideately and no other operations to be performed. This can be done with single try-catch.
Use supervisorScope with individual try-catch for each tasks when you want the independent tasks.
So, we have understood the difference between the coroutineScope and supervisorScope.
That’s all for now. Thanks.
Please feel free to reach out to me on LinkedIn.