...

/

More on Constructing a Coroutine Scope

More on Constructing a Coroutine Scope

Learn how to use viewModelScope and lifecycleScope, create a coroutine, and create a scope for additional calls.

viewModelScope and lifecycleScope

In modern Android applications, instead of defining our own scope, we can also use viewModelScope or lifecycleScope. They work almost identically to what we’ve just constructed. They use Dispatchers.Main and SupervisorJob, and they cancel the job when the view model or lifecycle owner gets destroyed.

Press + to interact
public val ViewModel.viewModelScope: CoroutineScope
get() {
val scope: CoroutineScope? = this.getTag(JOB_KEY)
if (scope != null) {
return scope
}
return setTagIfAbsent(
JOB_KEY,
CloseableCoroutineScope(
SupervisorJob() +
Dispatchers.Main.immediate
)
)
}
internal class CloseableCoroutineScope(
context: CoroutineContext
) : Closeable, CoroutineScope {
override val coroutineContext: CoroutineContext = context
override fun close() {
coroutineContext.cancel()
}
}

Using viewModelScope and lifecycleScope is convenient and is recommended if we do not need any unique context as a part of our scope (like ...