In LiveData, how do map and switchMap differ, and when would you add distinctUntilChanged to the chain?
answer
- value out versus LiveData out
- drop the previous inner source
- setValue never compares values
- MediatorLiveData under all three
basics
~20 smap 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.
solid answer
~50 s`map { }` turns each source value into another value, on the main thread, so it suits cheap reshaping such as status to label text. `switchMap { }` is for when the value selects a **stream**: its function returns a `LiveData`, and each time the source emits, the result stops forwarding the previously returned LiveData and follows the new one. That is the selected-order-id to order-status case, and it means a late update for the old order is no longer forwarded. `distinctUntilChanged()` forwards a value only when it is not `equals()` to the previous one, which matters because `setValue` notifies even for equal values; add it after a `map` that often yields the same output or before an expensive observer. All three are built on `MediatorLiveData`, so they only listen to their source while the result is observed.
code
kotlin · 13 linesfun trackingState(
status: LiveData<OrderStatus>,
courier: LiveData<CourierLocation>,
): LiveData<TrackingUi> {
val result = MediatorLiveData<TrackingUi>()
fun update() {
val s = status.value ?: return
result.value = TrackingUi(s, courier.value)
}
result.addSource(status) { update() }
result.addSource(courier) { update() }
return result.distinctUntilChanged()
}go deeper
Recall that map changes each value and switchMap follows a different LiveData chosen by the value.
Explain how switchMap drops the old inner source, why setValue's lack of equality checks makes distinctUntilChanged useful, and that map runs on the main thread.
Use the MediatorLiveData model to explain laziness and initial values, and reach for addSource when inputs must be combined.
Judge when hand-written MediatorLiveData plumbing has grown enough to justify moving that logic to a richer stream library.
## Deriving one LiveData from another The Lifecycle library ships three transformations as Kotlin extension functions on `LiveData`: `map`, `switchMap` and `distinctUntilChanged`. Two release changes matter when reading older code: - Since Lifecycle **2.6.0** they are written in Kotlin. Kotlin code calls them as `source.map { ... }`; the old `Transformations.map(source) { ... }` form is no longer source-compatible in Kotlin. Java still calls `Transformations.map(source, function)`. - Since Lifecycle **2.7.0** they live in the main `lifecycle-livedata` artifact; the separate `-ktx` module's files were moved into it. ## map: reshape each value `map` returns a new LiveData whose value is `transform(sourceValue)` for every value the source emits. Use it for cheap, synchronous reshaping, such as turning an `OrderStatus` into the text a label shows. - `transform` runs **on the main thread**, so it must stay cheap. Filtering a large list or reading a database inside it janks the UI. - One input value gives exactly one output value. ## switchMap: swap the LiveData you follow `switchMap` takes a function that returns a **LiveData**, not a value. Each time the source emits, it calls the function, stops listening to the LiveData it returned last time, and forwards the values of the new one. The classic case is an id that selects a stream: ```kotlin val selectedOrderId = MutableLiveData<String>() val orderStatus: LiveData<OrderStatus> = selectedOrderId.switchMap { id -> repository.observeStatus(id) } ``` When the user picks another order, the previous order's LiveData is removed as a source, so a late update for order A is no longer forwarded to the screen showing order B. If the function returns the same LiveData instance again, the subscription is kept; if it returns `null`, the old source is dropped and nothing new is followed. Using `map` here instead would produce a `LiveData<LiveData<OrderStatus>>` that nobody unwraps. ## distinctUntilChanged: suppress repeats `setValue` never compares old and new values, so a source that re-sets an equal `OrderStatus` makes every downstream observer run again. `distinctUntilChanged()` forwards a value only when it is not `equals()` to the last one it forwarded. Add it: - after a `map` whose output often repeats, such as several statuses mapping to the same label; - before an expensive observer that rebinds a list or restarts an animation; - on sources that re-emit the same snapshot whenever anything upstream changes. It relies on `equals()`, so the values need meaningful equality, as data classes have. ## All three are MediatorLiveData underneath Each transformation creates a `MediatorLiveData` and calls `addSource` on its input. That explains two behaviours: 1. **They are lazy.** A `MediatorLiveData` listens to its sources only while it has an active observer of its own. With nobody observing the result, `map` receives no updates and `switchMap` stops listening to its inner LiveData. 2. **They have an initial value.** When the source already holds a value, `distinctUntilChanged` (since 2.6.0) and `map` and `switchMap` (since 2.7.0) set the result's value at creation, so Compose's `observeAsState()` shows the right value on the first composition. Later updates still flow only once something observes the result. `MediatorLiveData` is also what you use directly when no transformation fits, such as combining an order's status with its courier's location. Call `addSource` for each input and set the mediator's value from either callback; `removeSource` stops listening to one input. Adding the same source again with a different observer throws `IllegalArgumentException`. ## Common mistakes - **A new LiveData per call.** A ViewModel function such as `getStatus(id)` that returns a fresh repository LiveData every time forces the UI to unregister from the old one and register on the new one by hand, and a recreated screen that calls it again gets yet another instance. The Android guide shows this as the pattern to avoid; hold the id in a `MutableLiveData` and expose one `switchMap` result instead. - **Heavy work in `map`.** The guide's own counter-example filters a list and queries a DAO inside a transformation and warns that it janks the UI, because the function runs on the main thread. - **Expecting values with no observer.** Reading `value` on a transformation nobody observes returns at most the initial value computed at creation, not the source's later updates. | need | use | |---|---| | reshape each value | `map` | | follow a LiveData chosen by the current value | `switchMap` | | drop equal consecutive values | `distinctUntilChanged` | | merge two or more inputs | `MediatorLiveData` with `addSource` |
- How do you combine two LiveData sources, such as an order's status and its courier's location, into one?Create a MediatorLiveData and call addSource for each input, setting the mediator's value from either callback using both inputs' current values. The mediator connects to its sources only while it has an active observer, and removeSource stops listening to one of them.
- Why does a LiveData produced by map stop updating when nothing observes it?map is a MediatorLiveData that listens to its source only while it has an active observer. With no observer, onInactive() disconnects the source, so new source values are not transformed until something observes the result again, at which point it picks up the source's latest value.
- map and switchMap are interchangeable; switchMap is just the asynchronous version.
- switchMap keeps forwarding values from every LiveData it has returned before.
- The map function runs on a background thread, so heavy work inside it is fine.
- LiveData already ignores equal values, so distinctUntilChanged changes nothing.
- Transformations keep running even when nobody observes the result.
Assumes Lifecycle 2.11; the transformations became Kotlin extension functions in 2.6.0 and moved into lifecycle-livedata in 2.7.0, when map and switchMap also began setting an initial value.