https://kotlinlang.org logo
#coroutines
Title
# coroutines
h

haroldadmin

06/28/2019, 5:22 PM
What coroutine scope do you use to launch coroutines in classes that don’t have a lifecycle? I’m creating a NotificationManager class in an Android application, and I need to use coroutines for taking some database related tasks off the main thread. This class will be used as a singleton in the project via dependency injection. Should I implement the
Coroutine Scope
interface in it? There will be no lifecycle callback to cancel the running coroutines in this scope, though. Since a single instance of this class will be shared with the entire application, any coroutines launched in this scope will be equivalent to launching them in the global scope. So should I just avoid the ceremony and use GlobalScope in this class?
l

louiscad

06/28/2019, 6:06 PM
val AppScope = CoroutineScope(Dispatchers.Main)
You can then use if for coroutines that are scoped to the entire process. Beware of what you launch there though as no cancellation would take place right after the user leaves the UI.
h

haroldadmin

06/28/2019, 6:13 PM
In this case wouldn’t
AppScope
serve the same purpose as GlobalScope?
l

louiscad

06/28/2019, 6:38 PM
@haroldadmin
GlobalScope
runs on the multithreaded
Dispatchers.Default
. Depends on what you're calling.
h

haroldadmin

06/28/2019, 7:01 PM
You’re right, thanks for pointing out the difference.
10 Views