Reputation: 29877
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?
Upvotes: 10
Views: 10717
Reputation: 13223
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.
Upvotes: 14