skip to content

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

level: middleimportance: must knowfreq 72%

answer

  1. which thread is calling
  2. one runs now, one later
  3. a single pending slot
  4. only the last post survives

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.

solid answer

~40 s

`setValue` is `@MainThread`: it throws `IllegalStateException` from a background thread, and on the main thread it stores the value and notifies active observers during the call. `postValue` can be called from any thread: it puts the value in a single pending slot and schedules one task on the main thread that later calls `setValue`. If you post again before that task runs, the slot is simply overwritten, so a worker that posts 1, 2, 3 in quick succession may deliver only 3. Posting is also deferred: `postValue("a")` followed by `setValue("b")` on the main thread ends with `"a"`. So use `setValue` (or `value =`) on the main thread, `postValue` from background threads for state where only the newest value matters, and switch to the main thread when every value must arrive.

code

kotlin · 16 lines
kotlin
private val _progress = MutableLiveData<Int>()
val progress: LiveData<Int> = _progress

fun uploadOnWorkerThread(chunks: List<ByteArray>) {
    chunks.forEachIndexed { index, chunk ->
        send(chunk)
        // Safe off the main thread; posts made before the main thread
        // runs the pending task collapse into the newest value.
        _progress.postValue((index + 1) * 100 / chunks.size)
    }
}

fun resetFromClick() {
    // Main thread: delivered to active observers during this call.
    _progress.value = 0
}

go deeper

for a junior

Recall the thread rule: setValue only on the main thread, postValue from any thread, and that value = in Kotlin calls setValue.

for a middle

Explain the pending slot behind postValue, why rapid posts collapse into the last value, and why postValue then setValue ends with the posted value.

for a senior

Spot where coalescing loses data that matters, such as events or progress steps, and move those updates to the main thread or off LiveData.

for a principal

Decide whether background-produced streams belong in LiveData at all, given that every update funnels through one main-thread slot.

## Two ways to change a MutableLiveData `LiveData` itself exposes no public setter. `MutableLiveData` makes two of them public, `setValue(T)` and `postValue(T)`; in Kotlin, `liveData.value = x` calls `setValue`. They differ in **which thread may call them** and **when the change takes effect**. | | `setValue` | `postValue` | |---|---|---| | caller thread | main thread only | any thread | | when observers hear about it | during the call | later, when a task runs on the main thread | | `getValue()` right after the call | the new value | possibly still the old value | | several calls in quick succession | each one dispatched | may collapse into the last one | ## setValue: synchronous and main-thread only `setValue` is annotated `@MainThread` and checks it at runtime: from any other thread it throws `IllegalStateException` with the message "Cannot invoke setValue on a background thread". On the main thread it stores the value, advances the LiveData's internal version, and dispatches straight away to every **active** observer. It does not compare the new value with the old one, so setting an equal value notifies observers again. ## postValue: one pending slot and one main-thread task `postValue` is the thread-safe path, and its implementation explains every surprise it causes: - Under a lock, it writes the value into a single **pending** slot. - If the slot was empty, it schedules one task on the main thread. - If a task was already scheduled, it only overwrites the slot and returns. - When the task runs, it takes whatever is in the slot and calls `setValue` with it. The consequence is **coalescing**. A worker thread that calls `postValue(1)`, `postValue(2)` and `postValue(3)` before the main thread reaches the task leaves only `3` in the slot, and observers receive `3` once. The values `1` and `2` are not queued anywhere; the library's documentation says plainly that only the last value is dispatched. That is harmless for state such as a download percentage, where only the newest number matters, and a bug when each value is a separate event. ## The ordering trap Because `postValue` defers, mixing it with `setValue` can run in a surprising order. The library documents this example, executed on the main thread: ```kotlin liveData.postValue("a") liveData.setValue("b") ``` `"b"` is set first; later the posted task runs and overwrites it with `"a"`. In the same way, reading `getValue()` immediately after `postValue` can return the previous value, because the post has not run yet. ## Choosing between them 1. **Already on the main thread** (a click listener, a coroutine on `Dispatchers.Main`): use `setValue`, or `value =` in Kotlin. It is immediate and predictable. 2. **On a background thread, publishing state where only the newest value matters**: `postValue` is fine and saves a thread switch. 3. **On a background thread, publishing values that must each arrive**: switch to the main thread first (for example `withContext(Dispatchers.Main)` in a coroutine) and call `setValue`, or reconsider whether LiveData is the right carrier for that stream. 4. **In local JVM unit tests**: LiveData's thread checks and posted tasks go through an executor that relies on Android's main looper, which a plain JVM test does not have. `InstantTaskExecutorRule` from `androidx.arch.core:core-testing` makes them run synchronously on the test thread. ## Why postValue was designed this way Scheduling one main-thread task per update would let a busy worker flood the main thread's message queue. With a single pending slot, a producer emitting thousands of values per second causes at most one scheduled task at a time, and the UI renders the freshest value when it gets the chance. The price is the coalescing described above, which is a deliberate trade, not a defect. Inside the `liveData { }` coroutine builder you call neither setter: `emit(value)` switches to `Dispatchers.Main.immediate`, sets the value there, and suspends until it is set, so values emitted one after another from a coroutine are each set in turn rather than collapsed the way rapid `postValue` calls are (an observer that is inactive at the time still receives only the latest). ## Related details - `observe`, `observeForever` and `removeObserver` are main-thread-only as well, and each throws an `IllegalStateException` from a background thread. - `MutableLiveData` is a Java class, so a Kotlin `MutableLiveData<String>` still accepts a nullable value through its setters; Lifecycle's `NullSafeMutableLiveData` lint check flags that case. - A ViewModel usually keeps the `MutableLiveData` private and exposes it as read-only `LiveData`, so only one class can call either setter.

  • Why can reading getValue() right after postValue return the old value?
    postValue only stores the value in a pending slot and schedules a main-thread task; the stored value LiveData returns from getValue() changes when that task runs and calls setValue. Until then, getValue() still returns the previous value, and isInitialized can still be false for a LiveData that had no value.
  • How do you unit-test a ViewModel that calls postValue on a plain JVM?
    Add InstantTaskExecutorRule from androidx.arch.core:core-testing. It replaces the executor LiveData uses, so main-thread checks pass on the test thread and posted tasks run synchronously, and the test can read the value or observe it with observeForever right after the call.

postValue is a single hook for a note on the fridge: anyone can hang a note, each new one replaces the last, and whoever checks the hook later reads only the newest. setValue is replacing the note yourself while standing at the fridge, so everyone already in the kitchen sees it at once.

  • postValue queues every value, so observers see each one in order.
  • setValue is safe from any thread because LiveData synchronises internally.
  • postValue is just setValue for background threads, with identical timing.
  • After postValue, getValue immediately returns the new value.
  • setValue skips observers when the new value equals the old one.