androidengineers.Book a session
โ† All interview questions
Android BasicsIntermediate3 min

Returning to a Fragment duplicates UI updates. Which lifecycle would you investigate?

Answer

Look for collectors registered each time onViewCreated runs but cancelled only when the Fragment itself is destroyed. A Fragment on the back stack can remain alive after its view is destroyed. Creating another view can therefore add another collector.

Tie rendering work to viewLifecycleOwner, and release view binding in onDestroyView. Also inspect listener registration: not every duplicated update comes from Flow.

Example

Inside onViewCreated, with an existing ViewModel and render function:

viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { state ->
            render(state)
        }
    }
}

Collection stops below STARTED and restarts when the view becomes active again. Destroying the view cancels the outer job. If collecting two never-ending flows in this block, launch a separate child coroutine for each; the first collect otherwise prevents reaching the second.

How to verify

Navigate away and back several times, then emit one state update. Check that the current view renders once and the old binding is no longer referenced. Also background and resume the activity.

Follow-up to practise

Does stopping collection stop the network producer? Not necessarily. A shared upstream flow can keep running according to its sharing policy and other subscribers. Inspect the producer as well as the UI collector.

References

Android Developers: Fragment lifecycle

Android Developers: Lifecycle-aware coroutines

Mark this when you can explain the answer in your own words.

Share & Help Others

Help fellow developers prepare for interviews

Sharing helps the Android community grow ๐Ÿ’š

Keep practising