6

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?

Sam Chen
  • 7,597
  • 2
  • 40
  • 73

2 Answers2

4

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.

Sam Chen
  • 7,597
  • 2
  • 40
  • 73
J.Grbo
  • 435
  • 5
  • 11
4

It won't auto-cancel. It stays open for any number of jobs to be launched on it. However, you may want to give the scope a SupervisorJob() as its root context if you don't want it to be killed by any child jobs completing exceptionally. If that happened, subsequent coroutines on the scope wouldn't start.

private val backgroundScope = CoroutineScope(SupervisorJob())

The reason lifecycleScope and viewModelScope are automatically cancelled when their associated class is destroyed is because under the hood, Jetpack subscribes to the lifecycle of the associated class and manually cancels the scope in onDestroy().

Tenfour04
  • 83,111
  • 11
  • 94
  • 154