Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lifecycleScope.launch vs coroutine inside onViewCreated

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?

like image 780
Johann Avatar asked Jan 13 '20 13:01

Johann


People also ask

What is LifecycleScope launch?

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.

What is the difference between launch and async in Kotlin coroutines?

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.

When should you not use coroutines?

Answer: a. You should not use them for any foreground task.


1 Answers

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.

like image 139
Emmanuel Avatar answered Oct 12 '22 02:10

Emmanuel