skip to content

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%

answer

  1. not deprecated, still a cost
  2. data layer before UI
  3. bridges in both directions
  4. lifecycle gating must be rebuilt
  5. five-second grace period

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.

solid answer

~40 s

LiveData is not deprecated, so this is a cost decision, not a forced one. It is main-thread-bound, has few operators, and the Android guide advises against it in the data layer, while new Compose and Kotlin code expects Flow. I would move inside out: repositories return `Flow` and ViewModels keep their public LiveData through `asLiveData()`, so no fragment changes; then, screen by screen as features touch them, ViewModels expose `StateFlow` and the UI collects with `repeatOnLifecycle(STARTED)` or `collectAsStateWithLifecycle()`, with `observeAsState()` as a stopgap in Compose and `asFlow()` for remaining LiveData sources. The traps are behaviour LiveData gave for free: no delivery while stopped, the 5-second keep-alive in `asLiveData()` and `liveData { }`, and notifications for equal values. Stable or Java-heavy screens may keep LiveData indefinitely.

code

kotlin · 8 lines
kotlin
class OrderTrackingViewModel(repository: OrderRepository) : ViewModel() {
    // Step 1: the repository now returns Flow<OrderStatus>;
    // fragments still observe LiveData, unchanged.
    val status: LiveData<OrderStatus> =
        repository.observeStatus().asLiveData()
    // Upstream collection is cancelled only if no observer
    // returns within the default 5-second timeout.
}

go deeper

for a junior

Recall that LiveData is still supported and that asLiveData and asFlow convert between LiveData and Flow.

for a middle

Explain how the 5-second timeout in asLiveData and liveData { } survives a rotation, and how a cancelled block restarts.

for a senior

Name the behaviours a hand-written Flow collection must reproduce, from stopped-state gating to equal-value notifications, and test them before switching.

for a principal

Weigh migration cost against LiveData's limits per module, set an incremental rule rather than a project, and accept LiveData as a valid long-term end state where it fits.

## The decision is not "is LiveData deprecated?" It is not. Lifecycle 2.11 still ships `LiveData`, `MediatorLiveData` and the transformations, and existing code keeps working. The real question is whether moving a working codebase costs the team less than LiveData's limits cost it, and a lead should be able to argue both sides. **Reasons to move:** - LiveData is bound to the main thread: observers, `setValue` and transformation functions all run there, and its operators stop at `map`, `switchMap` and `distinctUntilChanged`. Combining sources means hand-written `MediatorLiveData`. - The Android guide advises against LiveData in the data layer, because it "is not designed to handle asynchronous streams of data", and recommends Flow there, converted with `asLiveData()` in the ViewModel if the UI still wants LiveData. - Android's architecture recommendations expose UI state as `StateFlow` and collect it with `collectAsStateWithLifecycle`; new Compose screens and Kotlin-first libraries are written against Flow. - Delivery quirks, such as a last value replayed to new observers and coalesced `postValue` calls, have produced workarounds the team keeps maintaining. **Reasons to keep it, for now:** - Stable screens that are rarely touched gain nothing from churn. - Java modules use LiveData naturally, while Flow is awkward to consume from Java. - LiveData's lifecycle gating comes for free; Flow collection has to be made lifecycle-aware by hand, and getting that wrong is a regression. - The same engineering time may buy more elsewhere. ## A sensible order: inside out, screen by screen 1. **Data layer first.** Repositories return `Flow`. Existing ViewModels keep their public `LiveData` by calling `asLiveData()`, so fragments do not change. This removes LiveData from where it was never meant to be, at the lowest UI risk. 2. **Then one screen at a time.** When a screen is touched for a feature, or rewritten in Compose, its ViewModel exposes `StateFlow` and its UI collects lifecycle-aware: `repeatOnLifecycle(Lifecycle.State.STARTED)` in a fragment, `collectAsStateWithLifecycle()` in Compose. Until then, a Compose screen can read existing LiveData with `observeAsState()` from `androidx.compose.runtime:runtime-livedata`. 3. **Legacy sources last.** Where something still produces LiveData, such as an older DAO query or a library callback, `asFlow()` adapts it for Flow code. The resulting flow is conflated, so a slow collector sees only the newest value. 4. **Tests move with each screen**, from `InstantTaskExecutorRule` plus observers to coroutine test tooling. ## Semantics that do not carry over automatically The bridges preserve behaviour that LiveData code already relies on, and whoever replaces them must reproduce it on purpose: | LiveData behaviour | what the replacement must do | |---|---| | no delivery while the screen is stopped | collect inside `repeatOnLifecycle(STARTED)` or with `collectAsStateWithLifecycle` | | `asLiveData()` and `liveData { }` keep work alive for 5 seconds after the last observer leaves, so a rotation does not restart it | share the upstream with a similar grace period, as the guide's `WhileSubscribed(5_000)` does | | a `liveData { }` block cancelled for inactivity restarts from the beginning when observed again | decide whether a restart is acceptable, or keep the last value | | `setValue` notifies even for an equal value | a `StateFlow` drops equal values, so a repeated-value signal disappears | | a LiveData may start with no value | a `StateFlow` needs an initial value | The 5-second figure is the library's internal default (`DEFAULT_TIMEOUT`, 5000 ms) for both the `liveData { }` builder and `asLiveData()`; both accept `timeoutInMs`, or a `Duration` on API 26 and higher, to change it. A block that completed is not run again; a block cancelled for inactivity re-runs from the start, and `latestValue` exposes the last emitted value so it can resume sensibly. Since Lifecycle 2.7.0 the builder and `asLiveData()` ship in `lifecycle-livedata` itself rather than a `-ktx` artifact. ## How a lead frames it - **Set a rule, not a project.** New code uses Flow; old code converts when it is touched; nothing converts only for the sake of converting. - **Track the seams.** Every `asLiveData()` and `asFlow()` is a bridge to delete later; count them so progress is visible. - **Protect behaviour first.** Put tests around lifecycle-sensitive screens before switching how they collect. - **Accept a long tail.** Java modules or rarely changed screens may keep LiveData indefinitely, and that is a legitimate end state.

  • What happens to a liveData { } block or asLiveData() collection when the screen rotates, and when the user leaves for good?
    When the last observer goes inactive, cancellation is scheduled after the timeout, 5 seconds by default. A rotation re-observes well within that, so the work continues. If no observer returns in time, the block or collection is cancelled, and it restarts from the beginning the next time the LiveData becomes active.
  • How would you keep a migrated screen from collecting while it is in the background?
    Collect inside repeatOnLifecycle(Lifecycle.State.STARTED) from the fragment's view lifecycle scope, or use collectAsStateWithLifecycle() in Compose. Both stop collecting when the screen drops below STARTED and restart when it starts again, which reproduces the gating LiveData's observe gave automatically.

  • LiveData is deprecated, so everything must be rewritten immediately.
  • Swapping observe for lifecycleScope.launch { collect } is an equivalent drop-in replacement.
  • asLiveData stops collecting the moment the last observer goes away.
  • A cancelled liveData { } block resumes where it was suspended.
  • StateFlow and LiveData deliver exactly the same sequence of values.

Assumes Lifecycle 2.11, where LiveData is still supported and the liveData { } builder and asLiveData() ship in lifecycle-livedata (merged from the -ktx artifact in 2.7.0) with a 5-second default timeout.