简体   繁体   中英

Which coroutine scope should I use in android.app.Application?

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?

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM