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.
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.
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.
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.
Mark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow ๐