In an Android Fragment, why does the view have its own lifecycle, and what breaks when code ignores viewLifecycleOwner and onDestroyView?
answer
- the fragment can outlive its view
- replace plus addToBackStack
- observers pile up
- clear the binding in onDestroyView
basics
~20 sA Fragment can outlive its view: replaced with addToBackStack, it stops and runs onDestroyView, then builds a new view on return. Observing with the fragment as owner piles up observers, and a binding kept past onDestroyView leaks the old views.
solid answer
~40 sA `Fragment` has two lifecycles: its own, and its view's, exposed as `viewLifecycleOwner`. They diverge whenever the fragment survives without a view. The common case is `replace()` with `addToBackStack()`: the old fragment moves to `CREATED`, its view is destroyed and `onDestroyView()` runs, but the instance and its fields stay in the `FragmentManager`. When the user presses Back, the same instance runs `onCreateView` and `onViewCreated` again. If `onViewCreated` observes with `this` as the owner, every return adds another observer that lives until the fragment itself is destroyed, so updates fire several times. If a field keeps the view binding after `onDestroyView`, the whole old view hierarchy cannot be garbage-collected. The fix is to observe with `viewLifecycleOwner` and set the binding to `null` in `onDestroyView`.
code
kotlin · 18 linesclass LayersFragment : Fragment(R.layout.fragment_layers) {
private var _binding: FragmentLayersBinding? = null
private val binding get() = _binding!!
private val viewModel: EditorViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
_binding = FragmentLayersBinding.bind(view)
viewModel.preview.observe(viewLifecycleOwner) { bitmap ->
binding.previewImage.setImageBitmap(bitmap)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}go deeper
Know that a fragment has its own lifecycle plus a separate one for its view, and that onDestroyView can run while the fragment itself lives on.
Walk through replace with addToBackStack callback by callback, and explain why observers belong to viewLifecycleOwner and bindings are cleared in onDestroyView.
Diagnose duplicate updates and view leaks from a trace or heap dump back to the wrong lifecycle owner, and make the binding pattern a review rule.
Weigh how much screen logic should sit in fragments at all, and push view-bound work into lifecycle-aware components so the two-lifecycle trap cannot recur.
## Two lifecycles, one fragment A `Fragment` implements `LifecycleOwner`, so it has a `Lifecycle` that moves through `INITIALIZED`, `CREATED`, `STARTED`, `RESUMED` and `DESTROYED`. Its **view** has a separate `Lifecycle`, managed independently and exposed through `getViewLifecycleOwner()` (in Kotlin, `viewLifecycleOwner`) and `getViewLifecycleOwnerLiveData()`. The view lifecycle exists only while the fragment has a view: 1. `onCreateView()` returns a non-null `View` (or the `@LayoutId` constructor inflates one). 2. The view lifecycle owner is created, and `onViewCreated()` runs. This is where the documentation says to set up the view's initial state and start observing data that updates it. 3. Saved view state is restored, `onViewStateRestored()` runs, and the view lifecycle moves to `CREATED`, then follows the fragment up to `STARTED` and `RESUMED`. 4. On the way down, after exit animations finish and the view is detached from the window, the view lifecycle reaches `DESTROYED` and `onDestroyView()` runs. From then on `getViewLifecycleOwnerLiveData()` holds `null`. Two other callbacks frame everything: `onAttach()` runs before any lifecycle state change, when the `FragmentManager` takes the fragment, and `onDetach()` runs after the last one. ## When the fragment outlives its view The two lifecycles diverge in several everyday situations: - **Replace with the back stack.** If a transaction removes or replaces a fragment and calls `addToBackStack()`, the old fragment is only stopped. It sits in `CREATED`, its view is destroyed, and it is resumed with a **new** view when the user navigates back. - **`detach()`** destroys the view hierarchy while the `FragmentManager` keeps managing the fragment. - **Without the back stack**, a removed fragment goes all the way to `DESTROYED`, so both lifecycles end together. | Operation | Fragment instance | Fragment fields | Its view | |---|---|---|---| | Replaced with `addToBackStack()` | kept, stopped | kept | destroyed, rebuilt on return | | Replaced without the back stack | destroyed | lost | destroyed | | Configuration change | recreated by the `FragmentManager` | lost unless saved | rebuilt, view state restored | ## Bug 1: observers that pile up Suppose the photo editor's layers screen calls `preview.observe(this) { ... }` in `onViewCreated`. The owner is the fragment, whose lifecycle only ends at `DESTROYED`. Each trip to the back stack and back creates a new view and runs `onViewCreated` again, adding another observer, while the earlier ones stay registered. After two round trips three observers react to every update. If an observer captured a view from an earlier inflation, it writes into a view that is no longer on screen. Observing with `viewLifecycleOwner` ties each registration to one view: it is removed when that view's lifecycle reaches `DESTROYED`, and the next `onViewCreated` registers exactly one new observer. ## Bug 2: a binding that outlives its view A view-binding object holds references to every view in the layout. A fragment on the back stack is alive but has no view, so a binding field kept after `onDestroyView` pins the whole destroyed hierarchy in memory, a classic fragment view leak that leak-detection tools report after `onDestroyView`. The documented rule is that by `onDestroyView` **all references to the fragment's view should be removed**. The usual pattern is a nullable backing field, set in `onViewCreated` and cleared in `onDestroyView`, not in `onDestroy`, which may run much later or never while the fragment waits on the back stack. ## Catching these bugs before users do - Navigate forward and back twice on every fragment screen and count how often each update fires; a count that grows with each round trip is the observer bug. - Run a leak detector in debug builds and read its report after leaving a screen that sits on the back stack. - Rotate while a fragment waits on the back stack, then press Back, to exercise both the rebuilt view and the recreated instance. - In code review, treat `this` passed as the owner inside `onViewCreated`, and any non-nullable view field, as defects to question. ## Related rules interviewers probe - Tie lifecycle-aware work to `STARTED`: it guarantees the view exists, if one was created, and that a child fragment transaction is safe. - Fragments that are not `RESUMED` should not request focus or show the soft keyboard. - Add fragments from XML with `FragmentContainerView`, not the `<fragment>` tag, which can move a fragment beyond its `FragmentManager`'s state. - Do not reuse a fragment instance after it has been removed from its `FragmentManager`. - Order matters in both directions: moving up, the fragment's callback runs and then its `Lifecycle` event is emitted, followed by the view's; moving down, the view's event comes first, then the fragment's, then the callback.
- Which callbacks run on the old fragment when it is replaced with addToBackStack(), and which when the user presses Back?On replace it gets `onPause`, `onStop` and `onDestroyView`; it stays attached in `CREATED`, so `onDestroy` and `onDetach` do not run. On Back the transaction is reversed: the same instance runs `onCreateView`, `onViewCreated`, `onViewStateRestored`, `onStart` and `onResume`, while the fragment that replaced it is removed and destroyed.
- Why does a fragment's field survive the back stack but not a rotation?On the back stack the `FragmentManager` keeps the same instance, so its fields stay. A configuration change recreates the activity and its fragments as new objects, so fields are gone unless they were written to the saved instance state `Bundle` or held by an object that survives recreation. The `FragmentManager` restores the fragments and back stack itself.
A fragment on the back stack is like an actor between two runs of a play: the actor (the fragment and its fields) stays with the company, but the stage set (the view) is struck and rebuilt for the next run, so anything nailed to the old set must be nailed again to the new one.
- A fragment on the back stack keeps its view, so the binding stays valid.
- Observing with the fragment as owner is fine because the observer is lifecycle-aware.
- onDestroyView and onDestroy always run together.
- Clearing the binding in onDestroy is early enough to avoid a leak.
- The XML <fragment> tag behaves exactly like FragmentContainerView.