Is it a good practice to declare a coroutine scope inside the App
class instead of using a Globascope?
class App : Application() {
val applicationJob = Job()
companion object {
lateinit var instance: App
private set
lateinit var appDefaultScope: CoroutineScope
}
override fun onCreate() {
super.onCreate()
instance = this@App
appDefaultScope = CoroutineScope(Dispatchers.Default + applicationJob)
}
}
Here I defined a variable appDefaultScope
and initialized it in the App's onCreate
So anywhere in my code I could always do:
App.appDefaultScope.launch {
// some operations
}
The main difference with a GlobalScope that I see is that here I can always cancel the job and shut down all potentially stuck coroutines.
Are there are better alternatives to this?
The reason is that i have some object
functions that use coroutines and are not called from an activity (then I cannot provide them with a scope defined inside the activity) but need a scope for their operations.
An example of such object function is a Log that writes on a local database that can be called almost everywhere in the App.