Home > Blockchain >  Should we cancel the applicationScope created in the Application class?
Should we cancel the applicationScope created in the Application class?

Time:02-17

I've created an applicationScope in my Android Application class for operations that should outlive the viewModelScope and the lifecycleScope, like this:

class App : Application() {
    val applicationScope = CoroutineScope(...)

Should we automatically cancel the applicationScope in order to avoid leaks or for other reasons? I'm asking because I've seen some projects where people would call

applicationScope.cancel()

when their main activity would be destroyed or when the user wants to close the app. Is this necessary in some scenarios?

CodePudding user response:

There is no need to cancel an application level scope. It will be torn down when the process is killed. Source

class MyApplication : Application() {
  // No need to cancel this scope as it'll be torn down with the process
  val applicationScope = CoroutineScope(SupervisorJob()   otherConfig)
}

We don’t need to cancel this scope since we want it to remain active as long as the application process is alive, so we don’t hold a reference to the SupervisorJob. We can use this scope to run coroutines that need a longer lifetime than the calling scope might offer in our app.

  • Related