0

I am launching coroutine in activity onCreate like below(for understanding more on coroutines)

CoroutineScope(Dispatchers.IO).launch {
             for (i in 0 until 10000)
            {
                delay(500)
                LogUtils.debug("Coroutine", "Coroutine_Scope")
            }
        }

GlobalScope.launch {
            for (i in 0 until 10000)
            {
                delay(500)
                LogUtils.debug("Coroutine", "Global_Scope")
            }
        }

Now going from activity A to other activities in application without cancelling the coroutines. Now both the coroutines are running in background. I know globalscope will run till application is killed. But why coroutinescope is running? what is the exact difference between CoroutineScope(Dispatchers.IO).launch vs GlobalScope.launch ? For me both looks similar

siva1992
  • 363
  • 1
  • 2
  • 7
  • I answered before thinking about whether this was already asked. I think Marko Topolnik's answer on the linked question is most relevant to your specific question. – Tenfour04 Aug 25 '23 at 14:47

1 Answers1

0

Aside from the fact that GlobalScope's default dispatcher is Dispatchers.Default and that you created your own scope with Dispatchers.IO?

Behaviorally, there is no difference. These are both global coroutines that cannot be canceled except through the Job instance returned by launch().

The documentation for GlobalScope says not to use CoroutineScope(...).launch instead of using GlobalScope. I think the reason is that it sort of masks that you're launching a global coroutine.

Therefore, CoroutineScope().launch should never be used. It's a possible code smell that the author maybe doesn't understand what they're doing. But this is really just a matter of opinion, although it is endorsed by the official documentation.

It should be very rare that you need to run a global coroutine because they hang onto the references of everything they touch, which could be longer than the coroutine is useful. For instance, if you use a global coroutine in an Activity and access any properties or functions of the Activity, once the Activity finishes you have leaked everything in the Activity until the coroutine finishes. So, usually, we launch coroutines from lifecycleScope or similar coroutine scopes that are already set up to be cancelled at an appropriate time automatically. Or within your own classes, you can create a CoroutineScope and manage when to cancel it yourself.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154