Search code examples
androidkotlinkotlin-flow

Difference between launchWhenStarted and repeatOnLifecycle(STARTED) in collecting flows


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?


Solution

  • launchWhenStarted is just a one-time delay.

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

    Update:

    Notice that launchWhenStarted API is now deprecated because it could cause work to hang for a very long time.

    Currently for a one-shot one-time delay it's recommended to lifecycleScope.launch() a new job and use withStarted{ } method within it to cause a suspension until started state is reached.

    Detailed explanation of deprecation and replacements is in this this google tracker issue.