StateFlow and Android's Lifecycle

Android’s LiveData has a very handy behaviour: it only notify observers if the current Lifecycle is equal to ON_START or ON_RESUME.

Now that we have StateFlow with KMM, and create ViewModels that are platform agnostic (without LiveData). However, I’m struggling to simulate the same behaviour.

Is there a way to manually “pause” a job somehow and continue later in same point? For example, I could add a Lifecycle observer that pauses a Job when Lifecycle is not active (user can see the screen). I could also launch jobs but this could be problematic as I could redraw the UI unnecessary, for example.

I know we Android provides a viewLifecycleOwner.lifecycleScope but this is cancelled only when the view is destroyed…

This behaviour is important as some operations (like Fragment transactions) might crash depending on the current Lifecycle - and it also doesn’t make sense to show a snack bar if the user can’t see it.

Thanks in advance.

Sounds like you are looking for LifecycleOwner.whenResumed.

It has some gotcha’s if you change contexts or put in exception handling. The details are documented with Lifecycle.whenStateAtLeast.

2 Likes

Hey @nickallendev, that is exactly what I was looking for. Thanks a lot! :+1: