More on Constructing a Coroutine Scope
Learn how to use viewModelScope and lifecycleScope, create a coroutine, and create a scope for additional calls.
We'll cover the following...
We'll cover the following...
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.
public val ViewModel.viewModelScope: CoroutineScopeget() {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 = contextoverride 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 ...