Coroutine scope on Application class android

Based on the existing answers, I came up with this solution:

class YourApplication : Application() {

    companion object {
        var applicationScope = MainScope()
    }
    
    override fun onLowMemory() {
        super.onLowMemory()
        applicationScope.cancel("onLowMemory() called by system")
        applicationScope = MainScope()
    }
}

The onLowMemory() part is somewhat optional, but seems a good idea, since unfinished jobs could sit there for the lifetime of your application and use system resources.

We don’t need to cancel this scope in onDestroy since we want it to remain active as long as the application process is alive, as stated in the accepted answer.


GlobalScope will be suitable for Application instance.The get() method of taskRepository variable will work as Provider Pattern. It shouldn't be in app instance. It can be replace with lazy method.


NO , GlobalScope will NOT be suitable for Application instance.

As mention here in this article here:


There are multiple reasons why you shouldn’t use GlobalScope:

  • Promotes hard-coding values. It might be tempting to hardcode Dispatchers if you use GlobalScope straight-away. That’s a bad practice!

  • It makes testing very hard. As your code is going to be executed in an uncontrolled scope, you won’t be able to manage execution of work started by it.

  • You can’t have a common CoroutineContext for all coroutines built into the scope as we did with the applicationScope. Instead, you’d have to pass a common CoroutineContext to all coroutines started by GlobalScope.


So, one solution for this is to create your own scope like this: val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) But better yet, as pointed out by @Raman in the comments, use the equivalent that's already available to you:

kotlinx.coroutines.MainScope()

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.

Tags:

Android

Kotlin