androidkotlinkotlin-coroutinesandroid-threadingcoroutinescope

Android CoroutineScope Auto Cancel after It Finishes


I want to know whether coroutineScope will be auto-canceled after its work is finished. Say I create a coroutineScope in a custom class Rather Than ViewModel class or Fragment / Activity class:

class MyClass {
    private val backgroundScope = CoroutineScope(Dispatchers.Default)

    fun doSomething() = backgroundScope.launch {
        //do background work
    }
}

In this case, after the background work is done, would backgroundScope auto-cancel itself?


Solution

  • A CoroutineScope consists of a CoroutineContext. A CoroutineContext consist of 2 primary elements,a Job and a ContinuationInterceptor(usually just a CoroutineDispatcher), other elements are CoroutineExceptionHandler and CoroutineName.

    If a coroutine finishes it won't cancel the scope (that is its Job). Even if you cancel the coroutine's job it won't cancel the scope (that is its Job). Because each time you fire a coroutine using a specific scope, the coroutine's job becomes a child job of the scope's job.

    In your case backgroundScope, you did not specify a Job yourself, if you dig into the source code, you'll see that in the absence of a Job, a Job instance is provided..

    val coroutineJob = backgroundScope.launch { ... }
    

    When this coroutineJob finishes or is cancelled, it will not cancel the Job inside the backgroundScope, therefore the backgroundScope won't be cancelled.