Home > Mobile >  Difference between launchWhenStarted and repeatOnLifecycle(STARTED) in collecting flows
Difference between launchWhenStarted and repeatOnLifecycle(STARTED) in collecting flows

Time:02-15

As launchWhenStarted and repeatOnLifecycle(STARTED) provide completely different functionality (launchWhenStarted suspends the execution of the coroutine, and repeatOnLifecycle cancels and restarts a new coroutine), if the names of the new APIs were similar (for example, using launchWhenever for the restarting APIs), developers could’ve got confused and even use them interchangeably without noticing.

source

What is a simpler explanation for when to use which?

CodePudding user response:

launchWhenStarted is just a one time delay.

repeatOnLifecycle creates a suspending point that acts as a handler that runs provided block every time lifecycle enters provided state and cancel it whenever it falls below it (so for STARTED it happens when it gets stopped).

CodePudding user response:

repeatOnLifecycle restarts its coroutine from scratch on each repeat, and cancels it each time lifecycle falls below the specified state. It’s a natural fit for collecting most flows, because it fully cancels the flow when it’s not needed, which saves resources related to the flow continuing to emit values.

launchWhenX doesn’t cancel the coroutine and restart it. It just postpones when it starts, and pauses execution while below the specified state. They plan to deprecate these functions but I suspect there will need to be some replacement if they do, for the case where you are calling some time consuming suspend function and then want to do something when it’s done, like starting a fragment transaction. Using repeatOnLifecycle for this would result in redoing the time consuming action.

  • Related