In a fragment, why observe LiveData with viewLifecycleOwner rather than the fragment itself, and when does observeForever need removeObserver?
answer
- fragment outlives its view
- back stack keeps the fragment
- duplicate observers on return
- always active, never auto-removed
basics
~20 sA fragment outlives its view on the back stack, so observers bound to the fragment pile up and touch dead views; viewLifecycleOwner removes them in onDestroyView. observeForever is never removed automatically, so every such observer needs its own removeObserver call.
solid answer
~40 sA fragment on the back stack loses its view (`onDestroyView()`) but is not destroyed. If `onViewCreated()` calls `observe(this, ...)`, the old observer stays registered, and each return adds another one, so changes fire several callbacks, some holding a destroyed view or binding. `observe(viewLifecycleOwner, ...)` ties the observer to the view's lifecycle, so it is removed when the view is destroyed and only one exists per view; use it between `onCreateView()` and `onDestroyView()`. `observeForever(observer)` has no owner: the observer is always active, LiveData holds a strong reference to it and keeps counting as observed, and only `removeObserver(observer)` ends it. Use it in tests or lifecycle-free adapters, keep the observer reference, and remove it in the matching teardown.
code
kotlin · 14 linesclass OrderListFragment : Fragment(R.layout.fragment_order_list) {
private val viewModel: OrderListViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val emptyLabel = view.findViewById<TextView>(R.id.empty)
// Removed in onDestroyView, so a return from the back stack
// registers exactly one observer for the new view.
viewModel.orders.observe(viewLifecycleOwner) { orders ->
emptyLabel.isVisible = orders.isEmpty()
}
}
}go deeper
Recall that a fragment's view can be destroyed while the fragment lives on, and that viewLifecycleOwner follows the view.
Explain how observers pile up on return from the back stack, and why observeForever needs a removeObserver you keep a reference for.
Diagnose doubled callbacks or crashes on a cleared binding from the owner passed to observe, and audit observeForever calls for missing removal.
Set a team rule, enforced in review or lint, for which owner fragments use and where observeForever is allowed at all.
## Two lifecycles inside one fragment A `Fragment` has its own `Lifecycle`, and its **view** has a separate one, exposed as `viewLifecycleOwner` (`getViewLifecycleOwner()` in Java). The two diverge whenever the fragment outlives its view. The common case is the back stack: when another fragment replaces it, the first fragment's view is torn down (its view lifecycle reaches `DESTROYED` and `onDestroyView()` runs) while the fragment object stays alive in the `CREATED` state. When the user navigates back, `onCreateView()` and `onViewCreated()` run again with a new view and a new view lifecycle owner. ## What goes wrong with observe(this, ...) Observing in `onViewCreated()` with the fragment itself as the owner ties the observer to the **fragment's** lifecycle, not the view's: 1. First visit: observer A is registered. 2. The fragment goes to the back stack. Its view is destroyed, but the fragment is only stopped, so A stays registered, inactive. 3. The user returns. `onViewCreated()` runs again and registers observer B, a new lambda. A becomes active again as well. 4. Every change now calls both A and B. A still captures the old, destroyed view or binding, so it updates views nobody sees, keeps that old view hierarchy reachable, and can crash if it reads a binding reference cleared in `onDestroyView()`. Each further round trip adds one more observer. LiveData has no way to catch this: the owner is the same, the observer instances are different, and every registration is legal. ## The fix: viewLifecycleOwner Passing `viewLifecycleOwner` binds the observer to the view's lifecycle. It is removed exactly when the view is destroyed, and the next `onViewCreated()` starts again with a single fresh observer. The Android guide's own fragment examples observe in `onViewCreated()` with `viewLifecycleOwner`. Two rules follow: - Use it only while the fragment has a view, between `onCreateView()` and `onDestroyView()`. Outside that window there is no view lifecycle, so asking for the owner fails, and `getViewLifecycleOwnerLiveData()` holds `null` after `onDestroyView()`. - Keep the fragment's own lifecycle for work that has nothing to do with its views. ## observeForever: an observer with no owner `observeForever(observer)` registers an observer that LiveData treats as **always active**: - It receives every change, whatever any screen's lifecycle is doing. - It is **never removed automatically**; only `removeObserver(observer)` ends it. - LiveData keeps a strong reference to it. While it is registered, the LiveData counts as having an active observer, so `onActive()` work keeps running, a `MediatorLiveData` keeps its sources connected, and a `liveData { }` block is never cancelled for inactivity. | | `observe(owner, observer)` | `observeForever(observer)` | |---|---|---| | receives values | only while the owner is `STARTED` or `RESUMED` | always | | removed | automatically when the owner reaches `DESTROYED` | only by `removeObserver` | | typical caller | an activity, a fragment's view | tests, code with no lifecycle, adapters | ## Recognising the bug in a running app The owner mistake rarely crashes on the first visit, which is why it survives review. Typical symptoms: - A log line or analytics event inside `onChanged` appears twice, then three times, growing with every return to the screen. - A crash in an observer that reads a view binding the fragment cleared in `onDestroyView()`. - A leak report pointing at an old fragment view kept alive through a LiveData observer. `hasObservers()` and `hasActiveObservers()` on the LiveData help confirm it in a debugger or a test. ## When observeForever is right, and how to clean it up Use it where there is no `LifecycleOwner`, or where lifecycle gating would be wrong: a unit test asserting the values a ViewModel emits, or an adapter that turns LiveData into another API. The library's own `asFlow()` does exactly this: it calls `observeForever` when collection starts and `removeObserver` in a `finally` block when collection ends. In your own code: 1. Keep a reference to the observer instance; a lambda created inline at the call site cannot be removed later. 2. Pair every `observeForever` with a `removeObserver` in the matching teardown, such as an `@After` method in a test or the cancellation path of an adapter. 3. Call both on the main thread; each throws `IllegalStateException` from a background thread. 4. Never register one observer instance through both `observe` and `observeForever`; LiveData throws `IllegalArgumentException` ("Cannot add the same observer with different lifecycles").
- Why does an observeForever observer keep a liveData { } block or a MediatorLiveData's sources running?LiveData counts an observeForever observer as permanently active, so onInactive() is never called while it is registered. A MediatorLiveData therefore keeps its sources connected, and a liveData { } block never starts its inactivity timeout, until removeObserver is called.
- In a fragment, why register LiveData observers in onViewCreated rather than onCreate?In onCreate the fragment has no view yet, so there is no view lifecycle owner to bind to, and an observer bound to the fragment would outlive each view. onViewCreated runs once per view, which matches viewLifecycleOwner: one observer per view, removed in onDestroyView.
- Observing with this in a fragment is fine because LiveData removes observers when views go away.
- LiveData deduplicates observers, so registering again on return from the back stack is harmless.
- observeForever observers are removed when the app goes to the background.
- viewLifecycleOwner can be used in onCreate before the view exists.
- observeForever is the safer choice in UI code because it never misses a value.