dispatchLifecycleScope
CoroutineScope instance for the LifecycleOwner. By default, it uses the Dispatchers.Main.immediate dispatcher.
The lifecycleScope
instance is created automatically upon first access, from the factory set in LifecycleScopeFactory.
The type of CoroutineScope created is configurable via LifecycleScopeFactory.set.
The viewModelScope
is automatically cancelled when the LifecycleOwner's lifecycle's Lifecycle.State drops to Lifecycle.State.DESTROYED.
Samples
import dispatch.android.lifecycle.dispatchLifecycleScope
import dispatch.core.launchMain
import dispatch.internal.test.Sample5
fun main() {
//sampleStart
// This could be any LifecycleOwner -- Fragments, Activities, Services...
class SomeFragment : Fragment() {
init {
// auto-created MainImmediateCoroutineScope which is lifecycle-aware
dispatchLifecycleScope // ...
// active only when "resumed". starts a fresh coroutine each time
// this is a rough proxy for LiveData behavior
dispatchLifecycleScope.launchOnResume { }
// active only when "started". starts a fresh coroutine each time
dispatchLifecycleScope.launchOnStart { }
// launch when created, automatically stop on destroy
dispatchLifecycleScope.launchOnCreate { }
// it works as a normal CoroutineScope as well (because it is)
dispatchLifecycleScope.launchMain { }
}
}
//sampleEnd
}