I'm taking a course on Kotlin coroutines and I've had a few questions about the scope. First of all, I understand that it GlobalScope
is linked to the life cycle, if the activity (for example) dies before the coroutine finishes, it throws an exception, correct me if I'm wrong.
I have also come across two ways to implement CoroutineScope
, one would be to directly implement the interface and call get passing it the Dispatcher and the job, and the other that I have seen is creating an instance of it, what difference is there?
Finally, the other question I have is the method MainScope
that I have seen it used in some cases MainScope().launch
, and from what I have seen it already provides you with one CoroutineScope
, but when do I use one or the other? What is better?
It's tied to the application lifecycle , not the Activity. For that reason it is advised NOT to use it to create coroutines. If the Activity is closed, the coroutine will continue to run, and will continue to run until the application is closed.
It's pretty much the same except that if you implement the interface you don't need to reference the Scope to create a coroutine because the class instance itself (
this
) already works as the Scope.Implementing the interface:
Implementing the interface by delegating:
Creating an instance:
When you use the factory method
MainScope()
to create a Scope it is pretty much the same as creating it this way:CoroutineScope(SupervisorJob() + Dispatchers.Main)
. Here the important thing beyond how to create a Scope is how you will reference them later for when you need to cancel the coroutines that are still running. If you start creating Scopes every time you want to start a coroutine eg.MainScope().launch {...}
orCoroutineScope(Dispatchers.Main).launch {...}
you will not be able to cancel them and it would be practically the same as creating them with GlobalScope.The healthiest thing will always be to keep the reference to the Scope to be able to cancel the coroutines when necessary (for example during
onDestroy()
an Activity) taking advantage of structured concurrency so as not to have to cancel each and every one of the coroutines created one by one, but to do it canceling the Scope (or the Job of the Scope) that is referenced.