Home > OS >  Android repeatOnLifecycle in fragment inside ViewPager2
Android repeatOnLifecycle in fragment inside ViewPager2

Time:12-13

If I add the following code snippet to a "normal" fragment it gets started and cancelled as expected when navigating to and from the fragment, but if I add this to fragment inside a view pager 2 it is not cancelled even though the fragmens onPause method is invoked. Is this by design or am I missing something?

lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        try {
            while (isActive) {
                println("Fragment alive....")
                delay(1000)
            }
        } catch (ex: CancellationException) {
            println("Cancelled fragment...")
            throw ex
        }
    }
}

CodePudding user response:

I am no sure if I got your question right, but I can already tell that you're relaying on the wrong lifecycle event if you wish that your code gets executed when the Fragment is visible, for that you need to use repeatOnLifecycle(Lifecycle.State.RESUMED). Using this your code will start executing as soon as the Fragment is visible and gets cancelled when it gets paused. Using repeatOnLifecycle(Lifecycle.State.STARTED) your code will start executing when the Fragment is started (ready to get displayed) and gets cancelled when it gets stopped.

  • Related