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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.