Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

flowWithLifecycle(lifecycle, Lifecycle.State.STARTED) doesn't stop flows while App is in background

I’m trying to observe the result of the View Collection and upstream flows stopped.
But viewModel.testFlow is still collecting while the App is in the background.
Why can’t I observe the collection is stopped? Am I observing something wrong?

ViewModel:

val testFlow = flow<Int> {
    for (i in 1..100) {
        delay(1000)
        Timber.e("testFlow: EMIT = $i")
        emit(i)
    }
}

Activity:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

override fun onViewCreated() {
        lifecycleScope.launch {
            viewModel.testFlow
                .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED)
                .collect {
                    Timber.d("testFlow: $it Collected")
                }
        }
}

override fun onActivityPaused(activity: Activity) {
    super.onActivityPaused(activity)
    Timber.e("testFlow: onActivityPaused")
}

Logs
Lifecycle Diagram

https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda

>Solution :

You are using Lifecycle.State.STARTED state to start observing Flow, the corresponding method of the Activity when emission stops is onStop(). If onStop() method of Activity is called the emission and collecting will stop.

If you want to stop emitting and collection data when onPause method is called, you can use Lifecycle.State.RESUMED state.

When app goes to background onStop() method of Activity is called and when using Lifecycle.State.STARTED state to observe the Flow you should see the emission and collecting stop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading