Issue
I need a reference to coroutine scope on my android Application
. i did the following
class TodoApplication : Application() {
private var job = Job()
private val applicationScope = CoroutineScope(Dispatchers.Main + job)
val tasksRepository: TasksRepository
get() = ServiceLocator.provideTasksRepository(this, applicationScope)
}
Is this the way to do it. If so how can I cancel coroutines launched on this scope job.cancel()
Application class don’t have onDestroy method as Activities
Solution
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 hardcodeDispatchers
if you useGlobalScope
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 theapplicationScope
. Instead, you’d have to pass a commonCoroutineContext
to all coroutines started byGlobalScope
.
So, one solution for this is to create your own scope like this: But better yet, as pointed out by @Raman in the comments, use the equivalent that’s already available to you:val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
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.
Answered By – Ali Abu Harb
Answer Checked By – Katrina (FlutterFixes Volunteer)