skip to content

LiveData

The lifecycle-aware holder that delivers values only while its observer is started. Still asked because much production code predates Flow, and LiveData vs StateFlow is a standard follow-up.

on this pageshow

explore

questions

6

In LiveData, what does it mean that an observer registered with observe(this, observer) in an activity is lifecycle-aware?

level: juniorimportance: must knowfreq 75%

answer

  1. owner's lifecycle state decides delivery
  2. STARTED or RESUMED counts as active
  3. latest value on becoming active
  4. removed for you at DESTROYED

basics

~10 s

LiveData calls an observer registered with observe(owner, observer) only while the owner is STARTED or RESUMED, gives it the latest value when it becomes active, and removes it automatically when the owner reaches DESTROYED.

solid answer

~40 s

`observe(owner, observer)` ties the observer to the owner's `Lifecycle`. LiveData treats the observer as **active** only while that lifecycle is `STARTED` or `RESUMED`; changes made while the activity is stopped are not delivered, and when it starts again the observer receives just the latest value, not every intermediate one. If the LiveData already holds a value, a newly active observer gets it straight away, which is how a recreated activity repaints after rotation. When the owner reaches `DESTROYED`, LiveData removes the observer and drops its references to it and the owner, so the activity does not leak and no callback touches a dead view. Call `observe` on the main thread, usually in `onCreate`; callbacks arrive on the main thread too.

code

kotlin · 15 lines
kotlin
class OrderStatusActivity : AppCompatActivity() {
    private val viewModel: OrderStatusViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_status)
        val statusText = findViewById<TextView>(R.id.status)

        // Delivered only while this activity is STARTED or RESUMED;
        // removed automatically when it is DESTROYED.
        viewModel.status.observe(this) { status ->
            statusText.text = status
        }
    }
}

go deeper

for a junior

Recall the two active states, STARTED and RESUMED, and that the observer is removed for you when the owner is destroyed.

for a middle

Explain why a stopped activity gets only the latest value on return, and why observe belongs in onCreate rather than onResume.

for a senior

Show you know what awareness does not cover: main-thread rules, and a current value replayed to every new observer after rotation.

for a principal

Weigh the free lifecycle gating LiveData gives a View-based codebase against what a team must rebuild by hand when it collects streams instead.

## What "lifecycle-aware" means for an observer `LiveData` is an observable data holder from the Jetpack Lifecycle library. Observing it with `observe(owner, observer)` pairs the `Observer` with a `LifecycleOwner`: an activity, a fragment, a fragment's view, or anything else that exposes a `Lifecycle`. From then on, LiveData consults that lifecycle before every delivery. The rule is short: - An observer is **active** while its owner's lifecycle is at least `STARTED`, which means `STARTED` or `RESUMED`. - Only active observers have `onChanged` called. An activity that has been stopped (in the back stack, or behind another full-screen app) is in the `CREATED` state, so its observer is inactive and gets nothing. - When the owner reaches `DESTROYED`, LiveData removes the observer itself and drops its references to the observer and the owner. That is the whole meaning of **lifecycle-aware**: the subscription follows the owner's lifecycle, and the activity never has to start, stop or remove anything by hand. ## What happens to values while the observer is inactive LiveData holds **one current value**, not a history. While an activity is stopped, the value can change any number of times and none of those changes is delivered. When the activity starts again and its observer turns active, LiveData checks whether the value changed since the observer last saw it and, if so, delivers the **latest** value once. If nothing changed in between, it delivers nothing. | owner state | observer active? | what it receives | |---|---|---| | `INITIALIZED` or `CREATED` | no | nothing | | `STARTED` or `RESUMED` | yes | every new value, plus the current one on becoming active | | `DESTROYED` | removed | nothing, ever again | A brand-new observer counts as never having seen anything, so it receives the current value as soon as its owner is started, provided a value has been set at all. A `LiveData` created without a value calls no observer until the first `setValue` or `postValue`. ## Why rotation works without extra code On a configuration change such as rotation, the old activity is destroyed and a new one is created: 1. The old observer is removed at `DESTROYED`, so nothing touches the dead views. 2. The new activity calls `observe` again in `onCreate`. 3. When the new activity reaches `STARTED`, its fresh observer receives the value the `LiveData` still holds. When that `LiveData` lives in an object that survives the rotation (typically a ViewModel), the new screen repaints with the current data without reloading it. ## Where and how to call observe 1. **Call it in `onCreate`.** The Android guide names `onCreate` as the right place: it registers once per activity instance, and the activity has data to show as soon as it starts. Calling `observe` in `onResume` repeats the call on every resume, and a new lambda each time adds another observer. 2. **Call it on the main thread.** `observe` checks the thread and throws `IllegalStateException` from a background thread; `onChanged` is always dispatched on the main thread. 3. **Let LiveData remove it.** An observer added with an owner needs no `removeObserver` call in `onDestroy`. Edge cases worth knowing: - If the owner is already `DESTROYED`, `observe` silently ignores the call. - Passing the same owner and the same observer twice is ignored; passing the same observer with a **different** owner throws `IllegalArgumentException`. - A custom `LiveData` subclass can override `onActive()` and `onInactive()`, which run when the number of active observers goes from 0 to 1 and from 1 to 0. That is how a LiveData wrapping a price or location listener stays connected only while some screen is visible. ## The same rules in Compose A composable that reads LiveData through `observeAsState()` (from `androidx.compose.runtime:runtime-livedata`) gets the same behaviour, because that function registers with `observe` using the composition's current `LifecycleOwner`: - Values arrive only while that owner is `STARTED` or `RESUMED`. - The observer is removed when the composable leaves the composition or when the owner reaches `DESTROYED`, whichever comes first. - If the LiveData already holds a value, the returned `State` starts with it; otherwise it starts with the `initial` argument, or `null` without one. ## What lifecycle awareness does not give you It does not make LiveData thread-agnostic: a new value must still be set on the main thread or posted to it. And because the current value goes to every observer that becomes active, a value that stands for a one-off event (a snackbar, a navigation) is shown again after a rotation. That is a separate problem with its own fix.

  • What happens if the same Observer instance is passed to LiveData.observe with two different LifecycleOwners?
    LiveData throws IllegalArgumentException ("Cannot add the same observer with different lifecycles"), because one observer can follow only one lifecycle. Registering the same observer with the same owner a second time is silently ignored, so it never receives values twice from that call.
  • How can a custom LiveData subclass take advantage of its observers' lifecycle awareness?
    It overrides onActive() and onInactive(). LiveData calls onActive() when the number of active observers goes from 0 to 1 and onInactive() when it drops from 1 to 0, so a LiveData wrapping a price or location listener can register the listener only while some observing screen is started.

  • A stopped activity still receives every update; it just does not draw it.
  • The observer replays every value it missed while the activity was in the background.
  • You must call removeObserver in onDestroy or the activity leaks.
  • Observe in onResume, or the activity misses updates after returning to the foreground.
  • onChanged runs on whichever thread set the value.
open as a page

With MutableLiveData, when do you call setValue versus postValue, and what happens to values posted in quick succession?

level: middleimportance: must knowfreq 72%

basics

~20 s

setValue must run on the main thread and notifies active observers immediately. postValue works from any thread and schedules the update on the main thread; posts made before that task runs collapse, so only the last value arrives.

open as a page

In a fragment, why observe LiveData with viewLifecycleOwner rather than the fragment itself, and when does observeForever need removeObserver?

level: middleimportance: must knowfreq 64%

basics

~20 s

A 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.

open as a page

In LiveData, how do map and switchMap differ, and when would you add distinctUntilChanged to the chain?

level: middleimportance: should knowfreq 55%

basics

~20 s

map applies a function to each value; switchMap's function returns a LiveData, and the result follows only the latest one returned. distinctUntilChanged drops values equal to the last one, because setValue never compares and would re-run observers.

open as a page

After a rotation, a LiveData-driven order-tracking screen shows its 'Order cancelled' snackbar again; why does LiveData redeliver it, and how do you fix it?

level: seniorimportance: should knowfreq 58%

basics

~20 s

LiveData keeps its last value and delivers it to every new observer once started, so the recreated activity shows the message again. Handled-flag event wrappers were the old fix; today the message is UI state the ViewModel clears once shown.

open as a page

Your order-tracking app exposes LiveData from repositories to fragments; would you migrate it to Flow and StateFlow, and in what order?

level: principalimportance: should knowfreq 40%

basics

~20 s

Usually yes, gradually: move repositories to Flow first and bridge with asLiveData, then convert screens to StateFlow with lifecycle-aware collection as they are touched. Keep LiveData where screens are stable or Java-heavy; it is not deprecated.

open as a page