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

How to relaunch a coroutine on each Fragment.onResume call?

I have some coroutine that should be relaunched on each onResume() call of Fragment.

I have tried the following approach:

val renderer = ...
val outerFlow = ...
val lifecycleCoroutineScope = myFragment.viewLifecycleOwner.lifecycleScope

lifecycleCoroutineScope.launchWhenResumed {
   outerFlow.onEach(renderer::render).launchIn(this)
}

But it only works until the Fragment‘s view destroyed first time. I mean the second and the following onResume() calls became ignored.

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

So please help me to find out: how to properly launch my coroutine on each onResume() call?

>Solution :

I believe it doesn’t work because of calling launchIn(this). Please try to call another terminal operator, like collect:

lifecycleCoroutineScope.launchWhenResumed {
   outerFlow.collect(renderer::render)
}

In the docs they say that:

This API is not recommended to use as it can lead to wasted resources in some cases. Please, use the Lifecycle.repeatOnLifecycle API instead. This API will be removed in a future release.

With the Lifecycle.repeatOnLifecycle it will look something like the following:

lifecycleScope.launch {
    lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
        outerFlow.collect(renderer::render)
    }
}
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