Reputation: 17714
I need to call a suspend function in the on onCreate
method of android.app.Application
. Which coroutine scope should I use for that and why?
Upvotes: 4
Views: 3431
Reputation: 3579
By using SupervisorJob()
you can cancel the Global scope when the application class gets destroyed
Sample code
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
applicationScope.launch {
// action done in here
}
override fun onLowMemory() {
super.onLowMemory()
applicationScope.cancel()
}
onLowMemory()
is similar to onDestroy()
fun in application class
Upvotes: 1
Reputation: 29290
You can either use GlobalScope
or create your own scope in the Application class.
GlobalScope
is not bound to a lifecycle event, and that's what you'd want to use in the Application class.
Upvotes: 2