Search code examples
androidkotlin-coroutinesandroid-lifecycleandroid-jetpack

Difference between withStateAtLeast and whenStateAtLeast lifeCycle extension methods


There are two similar extension method in androidX lifecycle-ktx package with slightly different signature. withStateAtLeast and whenStateAtLeast. I read the doc but couldn't understand the difference in their behavior. An example on when we should use which one, would be appreciated.


Solution

  • Looking at the source code, whenStateAtLeast runs the given block when the lifecycle is at least in the required state and suspends the block if the lifecycle moves to lesser state while block is running.

    At the same time withStateAtLeast just waits for the lifecycle to be at least in the required state and runs the block. So it guarantees that the lifecycle state meets the requirement at the time it starts the block, but if the block suspends, by the time it's resumed, the lifecycle can be in lesser state or even destroyed.

    So in general withStateAtLeast is a good choice if you need to run a block when lifecycle reaches the state (e.g. user entered the screen) and finish its execution in any case, even if the user leaves the screen before the execution finished. whenStateAtLeast in its turn is useful when the block works with UI, it guarantees, that each time it resumes execution, the lifecycle is in proper state, so you can access UI safely.