In this example code:
class MyFragment: Fragment {
init {
lifecycleScope.launch {
whenStarted {
}
}
}
}
the code inside whenStarted only gets run when the fragment's lifecycle starts. It isn't clear to me though what exactly this does instead of just launching a coroutine inside of onViewCreated. The docs state:
If the Lifecycle is destroyed while a coroutine is active via one of the when methods, the coroutine is automatically canceled.
So is that the only reason why you would use lifecycleScope.launch? To have the coroutine automatically terminated if the lifecycle gets terminated?
LifecycleScope. A LifecycleScope is defined for each Lifecycle object. Any coroutine launched in this scope is canceled when the Lifecycle is destroyed. You can access the CoroutineScope of the Lifecycle either via lifecycle. coroutineScope or lifecycleOwner.
An async {} call is similar to launch {} but will return a Deferred<T> object immediately, where T is whatever type the block argument returns. To obtain a result, we would need to call await() on a Deferred. This fragment will print the output of the second coroutine before the output of the first.
Answer: a. You should not use them for any foreground task.
lifecycleScope
is a scope that is managed by a SupervisorJob
whose lifecycle is tied to the Fragment
's lifecycle. So just by using lifecycleScope
your coroutines will be cancelled when the underlying Lifecycle
instance (the Fragment
's LifecycleRegistry
in this case) is destroyed.
I believe that
lifecycleScope.launch { whenStarted {}}
is the more verbose form of lifecycleScope.launchWhenStarted {}
. As you would expect, the lambda passed into launchWhenStarted
will suspend until the Fragment
is on the started state.
So is that the only reason why you would use lifecycleScope.launch? To have the coroutine automatically terminated if the lifecycle gets terminated?
Cancellation is one of the benefits. Another benefit is that lifecycleScope.launch
uses the MainDispatcher
by default (unlike other builders which use Dispatches.Default
by default), so it guarantees that coroutines launched with it can perform UI operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With