Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 104 ยท App Architecture

LiveData and Lifecycle-Aware Components

Learn Android LiveData: MutableLiveData, observing with a lifecycle owner, MediatorLiveData, map and switchMap, DefaultLifecycleObserver, and how to migrate to StateFlow.

Before Kotlin Flow became the default, Android's answer to "how does the UI watch data without leaking or crashing?" was LiveData. It is an observable value holder that knows about Android lifecycles: it only delivers updates to observers that are visible, and it forgets them automatically when their screen is destroyed. Huge amounts of production code still use it, the Data Binding library and many tutorials assume it, and you will meet it in interviews. New code usually prefers StateFlow, but you need to read LiveData fluently and migrate it with confidence.

This lesson covers what LiveData is and why it exists, MutableLiveData and exposing it safely, observing with a lifecycle owner, MediatorLiveData, the map and switchMap transformations, the lifecycle classes underneath (LifecycleOwner, DefaultLifecycleObserver) and a migration path to StateFlow. The Android classes cannot run on this site, so the real code is read-only; the TryIts are plain-Kotlin stand-ins (a small LiveData with a fake lifecycle, and a real StateFlow doing the same job) and the prose says where the stand-in simplifies.

What LiveData is

LiveData has three properties that together solve a classic problem:

  1. It holds a value and notifies observers when it changes (like any observable).
  2. It is lifecycle-aware. Each observer is registered with a LifecycleOwner (an activity, a fragment's view, a navigation back stack entry). LiveData delivers updates only while the owner is at least STARTED. When the owner is stopped, updates pause; when it starts again, the observer immediately receives the latest value. When the owner is DESTROYED, the observer is removed, so there are no leaks and no updates to dead screens.
  3. It replays the current value to a new observer, so a screen that appears later still sees the current state.

It also always delivers on the main thread to observers, which is what views need. The cost is that it is Android-only (it lives in the androidx.lifecycle library, not plain Kotlin), has weak operators compared with Flow and, because values are stored, offers no good model for one-time events.

MutableLiveData and safe exposure

LiveData<T> is read-only; MutableLiveData<T> can be changed. A ViewModel keeps the mutable one private and exposes the read-only type, following the same rule you learned for state in ViewModel:

Kotlin
// read-only example
class TaskViewModel(private val repository: TaskRepository) : ViewModel() {

    private val _tasks = MutableLiveData<List<Task>>(emptyList())
    val tasks: LiveData<List<Task>> = _tasks                  // read-only for the UI

    fun load() {
        viewModelScope.launch {
            _tasks.value = repository.loadTasks()              // setValue: main thread only
        }
    }

    fun refreshFromWorker(list: List<Task>) {
        _tasks.postValue(list)                                 // postValue: any thread
    }
}

setValue (the value = property) must be called on the main thread and updates immediately. postValue can be called from any thread and posts the update to the main thread. If you call postValue twice before the main thread runs, only the last value is delivered. That is a frequent source of "missing" updates.

Observing with a lifecycle owner

Kotlin
// read-only example: Activity
viewModel.tasks.observe(this) { tasks ->
    adapter.submitList(tasks)
}

// read-only example: Fragment. Use the VIEW lifecycle owner
viewModel.tasks.observe(viewLifecycleOwner) { tasks ->
    adapter.submitList(tasks)
}

In a fragment, always pass viewLifecycleOwner, for the reason explained in Fragments: the fragment can outlive its view, and observing with the fragment itself registers a new observer each time the view is recreated. In Compose you convert with observeAsState() (from androidx.compose.runtime:runtime-livedata), which subscribes while the composable is in the composition.

The first stand-in is a miniature LiveData and a fake lifecycle. It shows the three behaviors: no delivery while stopped, the latest value on restart (intermediate values are not replayed) and automatic removal on destroy.

Kotlin A tiny LiveData with a lifecycle owner (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The real LiveData does the same with the owner's Lifecycle: it tracks active state through an internal observer and uses a version counter to avoid redelivering the same value, just as the stand-in does.

Transformations and MediatorLiveData

LiveData has a small set of operators in androidx.lifecycle (Kotlin extensions in lifecycle-livedata-ktx, now part of lifecycle-livedata).

  • map converts each value: val title: LiveData<String> = user.map { it.name.uppercase() }.
  • switchMap turns each value into a new LiveData and follows the latest one: ideal for a search query that triggers a repository call.
  • distinctUntilChanged skips repeats of an equal value.
  • MediatorLiveData combines several sources by adding each with addSource; it runs your lambda when any source changes. It only observes its sources while it has an active observer itself.
Kotlin
// read-only example: search results follow the query
class SearchViewModel(private val repository: SearchRepository) : ViewModel() {
    private val query = MutableLiveData("")
    val results: LiveData<List<Result>> = query
        .map { it.trim() }
        .distinctUntilChanged()
        .switchMap { text -> repository.search(text) }       // returns LiveData<List<Result>>

    fun onQueryChanged(text: String) { query.value = text }
}

// read-only example: combine two sources
val canSubmit = MediatorLiveData<Boolean>().apply {
    fun update() { value = !email.value.isNullOrBlank() && accepted.value == true }
    addSource(email) { update() }
    addSource(accepted) { update() }
}

These transformations run on the main thread. A slow map freezes the UI, so heavy work belongs in the repository or a coroutine.

One-time events: the classic trap

Because LiveData replays its current value, a "show a snackbar" event stored in LiveData fires again after a rotation, when the new observer subscribes. Old code worked around this with wrapper classes such as SingleLiveEvent or an Event<T> whose content could be consumed once. These are workarounds with their own races. Current guidance is to model events as state that the UI consumes (clear it after showing), exactly as UI State and One-Time Events explains.

The lifecycle classes underneath

LiveData is one citizen of a wider system, Lifecycle, in androidx.lifecycle:

  • LifecycleOwner is anything with a lifecycle: ComponentActivity, Fragment, a fragment's view (viewLifecycleOwner) and a navigation back stack entry. It exposes lifecycle.
  • Lifecycle has the states INITIALIZED, CREATED, STARTED, RESUMED and DESTROYED, and emits events (ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY) when moving between them.
  • DefaultLifecycleObserver is how your own classes react to lifecycle changes without the screen forwarding every callback, which keeps screens thin.
Kotlin
// read-only example: a component that manages itself
class LocationTracker(private val client: LocationClient) : DefaultLifecycleObserver {
    override fun onStart(owner: LifecycleOwner) { client.startUpdates() }
    override fun onStop(owner: LifecycleOwner) { client.stopUpdates() }
}

// in the Activity or Fragment
lifecycle.addObserver(LocationTracker(locationClient))       // in a fragment: viewLifecycleOwner.lifecycle

The tracker starts and stops with the screen, and the activity does not need a single line of start/stop code. The old @OnLifecycleEvent annotation is deprecated; use DefaultLifecycleObserver or LifecycleEventObserver. To run a coroutine while the lifecycle is in a given state, use repeatOnLifecycle(State.STARTED), which you met in Collecting Flows Safely with Lifecycle. To read the current state, use lifecycle.currentState.isAtLeast(State.STARTED).

Migrating from LiveData to StateFlow

StateFlow (see StateFlow and Flow in Compose) is the Kotlin-native equivalent of "holds a current value, replays it to new collectors". The mapping is direct:

LiveData StateFlow
MutableLiveData<T>(initial) MutableStateFlow<T>(initial)
LiveData<T> (exposed) StateFlow<T> via asStateFlow()
value = x / postValue(x) value = x (thread-safe, any thread)
observe(viewLifecycleOwner) { } repeatOnLifecycle(STARTED) { flow.collect { } }
observeAsState() in Compose collectAsStateWithLifecycle()
map, switchMap map, flatMapLatest
MediatorLiveData combine(a, b) { ... }
Needs a non-null initial value? No (can be unset) Yes, always

Behavior differences to remember:

  • A StateFlow always has a value and conflates: if you set equal values, collectors see one. LiveData notifies even for an equal value if you set it again.
  • StateFlow is not lifecycle-aware by itself; the lifecycle behavior comes from repeatOnLifecycle or collectAsStateWithLifecycle. Collecting in lifecycleScope.launch { } without it keeps running in the background.
  • Flow works in plain Kotlin and on any layer, which makes repositories and tests simpler. In viewModelScope, stateIn(scope, SharingStarted.WhileSubscribed(5_000), initial) turns a cold flow into a state holder.

You can migrate gradually. LiveData.asFlow() and Flow.asLiveData() convert in both directions, so a ViewModel can move first while screens keep observing LiveData.

The second stand-in does the same job as the previous one with the real kotlinx.coroutines StateFlow, a combine in place of a MediatorLiveData, and a collector that only runs while a pretend "started" flag is true, which is what repeatOnLifecycle does on Android.

Kotlin The same idea with StateFlow, combine and a lifecycle gate (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Compare the output with the first stand-in: the collector sees the current value on start, updates while started and only the latest state on restart, with the logic written as ordinary Kotlin.

Common mistakes

  • Observing with this in a fragment. Use viewLifecycleOwner.
  • Exposing MutableLiveData publicly. The UI can then change state; expose LiveData.
  • Calling setValue from a background thread. It throws; use postValue or switch to the main dispatcher.
  • Relying on postValue for every intermediate value. Rapid posts are conflated to the last one.
  • Using LiveData for one-time events. They replay after rotation; model events as consumed state.
  • Heavy work in map or switchMap lambdas. They run on the main thread.
  • Collecting a Flow with plain launch in a screen. It keeps running while the UI is stopped; use repeatOnLifecycle.
  • Forgetting the lifecycle dependency. observeAsState needs runtime-livedata; LiveData needs lifecycle-livedata.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An activity is stopped while its LiveData changes three times. When it starts again, what does the observer receive?

    LiveData holds one current value and delivers it when the owner becomes active again. Intermediate values are not replayed.
  2. 2. What is the difference between setValue and postValue?

    postValue schedules the update on the main thread. If called repeatedly before it runs, only the last value is delivered.
  3. 3. Which operator should you use when each query string must trigger a repository call that returns a LiveData?

    switchMap converts each value into a new LiveData and follows the most recent one, which fits search-as-you-type.
  4. 4. Which pair is the StateFlow equivalent of observe(viewLifecycleOwner)?

    StateFlow is not lifecycle-aware itself. Those APIs start collecting when the lifecycle is started and cancel when it stops.
  5. 5. How should a class start and stop a resource with the screen without the Activity forwarding callbacks?

    A lifecycle observer receives onStart, onStop and the other events directly, keeping screens small.

Summary

  • LiveData is a lifecycle-aware observable holder: it delivers only while the owner is started, replays the latest value, and removes observers on destroy.
  • Keep MutableLiveData private and expose LiveData; setValue is for the main thread, postValue for others (and conflates).
  • In fragments observe with viewLifecycleOwner.
  • map, switchMap, distinctUntilChanged and MediatorLiveData transform and combine sources on the main thread.
  • LifecycleOwner, Lifecycle and DefaultLifecycleObserver let components manage themselves; the @OnLifecycleEvent annotation is deprecated.
  • Do not use LiveData for one-time events; model them as state the UI consumes.
  • New code prefers StateFlow with repeatOnLifecycle or collectAsStateWithLifecycle; asFlow() and asLiveData() allow gradual migration.
  • The TryIts are plain-Kotlin stand-ins; the second uses the real kotlinx.coroutines StateFlow.

Next: Dependency Injection Concepts