0

I've seen two different uses of Coroutines at my company and I'm wondering which is best?

Usage 1

GlobalScope.launch(Dispatchers.IO) {
    loadMyData()
}

Usage 2

class MyClass(): GlobalScope {
. . .
    launch(Dispatchers.IO){
        loadMyData()
    }
. . . 
}

Is one better than the other? what are the pros and cons of each?

Dan Anderson
  • 1,062
  • 13
  • 26
  • `GlobalScope` is not recommended to use. Please, see thread https://stackoverflow.com/questions/54335365/why-not-use-globalscope-launch/ – Sergio Feb 06 '19 at 06:38
  • 1
    Possible duplicate of [Why not use GlobalScope.launch?](https://stackoverflow.com/questions/54335365/why-not-use-globalscope-launch) – Joffrey Feb 06 '19 at 20:08

1 Answers1

0

There's a third option as well

class MyClass(): CoroutineScope by GlobalScope

But there's a simple question which you should ask when considering how to implement it: Do you want MyClass to be a CoroutineScope which could be used by other parts of code base as well?

Most of the time the answer should be no and therefore it might be better to use GlobalScope directly.

Also I'm assuming, GlobalScope is the scope to use here and not go into details of why to consider not using it.

tynn
  • 38,113
  • 8
  • 108
  • 143