Fragments and their lifecycle

Why a Fragment has two lifecycles, what happens to its view on the back stack, and how to avoid leaks and duplicate observers. About 22 minutes.

Why it matters

  • A Fragment has two lifecycles: the Fragment itself and its view. Mixing them up is the number one Fragment bug.
  • Leaks and "the event fired twice" bugs after pressing Back almost always trace to this.
  • Many production apps still use Fragments: Navigation component, bottom sheets, dialogs, ComposeView hosts. You will meet them in legacy code and in interviews.
  • "Why viewLifecycleOwner?" is a favourite interview question.

The simple explanation

Think of a theatre play. The actor is the Fragment instance. The stage set is the view.

  • When the scene changes, the crew removes the stage set. The actor goes backstage and keeps their script and notes.
  • When the scene comes back, the crew builds a new set. The same actor walks on.
  • If the actor is sent home for good, both are gone.

So the instance can live longer than its view. That happens when a Fragment is on the back stack.

The real names:

CallbackMeaning
onAttachattached to the host Activity, context is available
onCreatethe instance is created, there is no view yet
onCreateView / onViewCreatedbuild the view, then set up listeners and collect flows
onStart / onResumevisible, then in the foreground
onPause / onStoplosing focus, then hidden
onDestroyViewthe view is going away: clear your binding
onDestroythe instance is finished (not called when it only sits on the back stack)
onDetachno longer attached to the Activity

The view has its own viewLifecycleOwner. It is valid only between onCreateView and onDestroyView. Asking for it outside that window throws an IllegalStateException.

The Fragment outlives its view
The Fragment outlives its view A Fragment is created, gets a view, starts and resumes, then pauses and stops; at onDestroyView its view is destroyed, and if the Fragment is kept on the back stack it stays alive with no view until the user goes back and a new view is created, otherwise onDestroy and onDetach end it. KEPT USER GOES BACK REMOVED Fragment created onAttach, onCreate New view created onCreateView, onViewCreated Started, resumed onStart, onResume Paused, stopped onPause, onStop View destroyed onDestroyView On the back stack Fragment alive, no view Fragment gone onDestroy, onDetach
On the back stack onDestroyView runs but onDestroy does not, so observe with viewLifecycleOwner, which ends with the view.

Notes

  • Instance and view are separate. On the back stack, onDestroyView runs but onDestroy does not. The fields survive. The view and everything that points at it must be released.
  • replace() with addToBackStack() keeps the old Fragment instance. replace() without it destroys the old Fragment.
  • Observe LiveData and collect Flows with viewLifecycleOwner, not this. With this, each return from the back stack adds one more observer to a Fragment that never died.
  • Clear view binding in onDestroyView. A Fragment on the back stack that still holds the binding keeps the whole old view hierarchy in memory.
  • Collect flows with repeatOnLifecycle(STARTED) on viewLifecycleOwner, so collection stops when the view is not visible.
  • Pass data with the arguments Bundle or Navigation arguments. The default FragmentFactory recreates a Fragment with its empty constructor, so constructor parameters are lost, and the app crashes if there is no empty constructor. A custom FragmentFactory is the only way around that.
  • ViewModel scope: by viewModels() is per Fragment, by activityViewModels() is shared with the host Activity, by navGraphViewModels() is shared inside one navigation graph.
  • Talk between Fragments with the Fragment Result API (setFragmentResult and setFragmentResultListener) or a shared ViewModel. setTargetFragment is deprecated.
  • Use childFragmentManager for Fragments nested inside a Fragment. Use parentFragmentManager for siblings.
  • A transaction committed after onSaveInstanceState throws IllegalStateException. Commit earlier, or use commitAllowingStateLoss only when losing the change is acceptable.
  • Inside a Fragment, host a ComposeView with ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed, so the composition is disposed with the view, not the Fragment.

Code example

A profile screen with view binding. The binding is cleared with the view. The flow is collected for the view's lifetime only.

class ProfileFragment : Fragment(R.layout.fragment_profile) {
 
    // Only valid between onViewCreated and onDestroyView.
    private var _binding: FragmentProfileBinding? = null
    private val binding get() = _binding!!
 
    // One ViewModel per Fragment; it survives rotation.
    private val viewModel: ProfileViewModel by viewModels()
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentProfileBinding.bind(view)
        binding.retryButton.setOnClickListener { viewModel.load() }
 
        // viewLifecycleOwner, not "this": stops with the view.
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect { render(it) }
            }
        }
    }
 
    private fun render(state: ProfileState) {
        binding.name.text = state.name
    }
 
    override fun onDestroyView() {
        _binding = null   // release the old view hierarchy
        super.onDestroyView()
    }
}

Why _binding is nullable: the property is only safe to read while the view exists. After onDestroyView a stale read crashes early instead of silently using a dead view. That is the point.

In production

The error dialog that appeared twice
  • Users open a list, tap an item and press Back. The next network error shows two "Network error" dialogs, and every further round trip adds one more.
  • The Fragment looked fine in a single run.
  • Cause: the Fragment observed a LiveData with this as the owner in onViewCreated. When the user returned from the back stack, onViewCreated ran again, but the Fragment instance was still alive. Each return added another observer.
The fix
  1. Reproduce it: open the screen, navigate forward, press Back, repeat. Add a log line in the observer and count the lines.
  2. Change the owner to viewLifecycleOwner. Observers are then removed with the view.
  3. Prefer one-off UI events as part of state that is marked as handled, so a rebuilt view does not replay them.
  4. Turn on LeakCanary in debug builds. It reports a Fragment view that stays in memory after onDestroyView.
The memory leak after every navigation
  • Memory use grows while users move between screens. An out-of-memory crash appears after long sessions on cheaper devices.
  • Cause: the Fragment kept binding as a plain field and never cleared it. After navigating forward, the old view hierarchy, with its images, stayed reachable from the Fragment on the back stack.
The fix
  • Set the binding to null in onDestroyView.
  • Also clear adapters set on a RecyclerView and other view references you stored in fields.
  • Check with a heap dump or LeakCanary after navigating away and back.

Common mistakes

  • Observing with this instead of viewLifecycleOwner. It gives duplicate observers after the back stack.
  • Reading binding after onDestroyView. A late callback from a coroutine or listener crashes. Cancel work with the view lifecycle.
  • Passing data through a constructor. The default factory recreates the Fragment with its empty constructor, so the data is lost, or the app crashes if there is no empty constructor. Use arguments.
  • Using the Activity as a shared bus. Casting the host to a listener interface couples the Fragment to one Activity. Use the Fragment Result API or a shared ViewModel.
  • Touching views in onCreate. There is no view yet. Use onViewCreated.
  • Assuming onDestroy runs when the user navigates away. With the back stack, only onDestroyView runs.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between a Fragment's lifecycle and its view's lifecycle?”

“Why should you observe LiveData with viewLifecycleOwner?”

“How do two Fragments communicate?”

Quiz

A Fragment is replaced with addToBackStack. Which callback runs on the old Fragment?

Which owner should you use to collect a Flow in onViewCreated?

Where should view binding be set to null?

What is the safe way to give a Fragment its start data?

0 of 4 answered

Mini task

Build two Fragments, ListFragment and DetailFragment, in one Activity. Navigate List to Detail with replace and addToBackStack.

  1. Add a log line to onCreate, onCreateView, onDestroyView and onDestroy in ListFragment.
  2. Observe a LiveData or StateFlow in ListFragment the wrong way (owner this) and log each emission.
  3. Go to Detail, press Back, and repeat three times. Count the log lines.
  4. Fix the owner to viewLifecycleOwner and count again.

You are done when you can explain which callbacks ran at each step and why the wrong version logged more lines each time.

Next: Intents and intent filters