跪拜 Guibai
← All articles
Android · Kotlin · Java

asLiveData Is a Lifecycle Bridge, Not a Data Ferry

By hai_android ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Lifecycle-aware collection has a hidden 5-second timer that can silently drop or restart a Flow stream when observers leave and return. Understanding that the "conversion" is really control-flow handoff, not data copying, is what prevents misconfiguring `timeoutInMs` and then wondering why updates stop.

Summary

The extension function Flow.asLiveData() looks like a simple conversion, but underneath it builds a three-layer mechanism that ties a Flow's collection to LiveData's observer lifecycle. The first layer wraps the Flow in a `collect { emit(it) }` suspend lambda, the second layer hands that lambda to a CoroutineLiveData builder, and the third layer — CoroutineLiveData itself — extends MediatorLiveData and runs a BlockRunner that decides when the collect coroutine actually starts and stops.

BlockRunner is the heart of the lifecycle switch. When observers are active, onActive() calls maybeRun(), which launches the collect block. When observers leave, onInactive() schedules a delayed cancellation with a default timeout of 5000ms. If an observer returns within that window, the pending cancellation is revoked and the same collect coroutine keeps running — this is how screen rotation avoids duplicate requests. If the timeout expires, the collect job is cancelled and the next activation restarts it from scratch, which explains the common "Flow stopped receiving updates" bug that `timeoutInMs = 0` fixes.

The mechanism also handles thread safety and initial values. emit() goes through LiveDataScopeImpl, which uses withContext to force writes onto the main thread and to make the write cancellable. StateFlow gets special treatment: its current value is pushed into the LiveData immediately at construction time, so the first screen never flashes empty. Two parameters matter: `context` controls where collection runs (default Main.immediate), and passing viewModelScope.coroutineContext can chain cancellation to ViewModel clearance; `timeoutInMs` trades resource release against resilience to brief inactive periods.

Takeaways
— asLiveData wraps a Flow in a `collect { emit(it) }` block and delegates the whole lifecycle handling to the liveData builder.
— The liveData builder creates a CoroutineLiveData, which extends MediatorLiveData to reuse addSource/removeSource for emitSource.
— CoroutineLiveData uses a SupervisorJob isolated from the caller's context, so cancelling on inactive doesn't kill viewModelScope or other parent jobs.
— Default collection runs on Dispatchers.Main.immediate; the context parameter can override this, but emit is always forced back to the main thread.
— BlockRunner starts collection in onActive() via maybeRun() and schedules a delayed cancel in onInactive() with a default timeout of 5000ms.
— If an observer re-subscribes within the timeout window, the pending cancellation is revoked and the same collect coroutine continues; past the window, collection restarts from zero.
— StateFlow's initial value is synchronized into the LiveData at construction time, regardless of lifecycle state, to avoid an empty first frame.
— Passing viewModelScope.coroutineContext as the context cancels the upstream Flow automatically when the ViewModel is cleared, skipping the 5-second wait.
— Setting timeoutInMs to 0 makes the LiveData cancel collection immediately on inactive, which is the common workaround for stale Flow data caused by the timeout expiring.
— emit() uses withContext with Main.immediate, which guarantees main-thread writes and makes the write point cooperative with cancellation, so cancelled blocks are ignored.
Conclusions

The 5-second grace period is a deliberate trade-off: it buys seamless screen-rotation behavior but turns Lifecycle-aware collection into a stateful system with a hidden timer that developers often trip over.

What people casually call a "conversion" between Flow and LiveData is really a transfer of control discretion, not a transfer of data; the lifecycle decides when the pipe is opened and closed.

The StateFlow initial-value shortcut exists purely to satisfy UI expectations — a cold Flow's laziness is fine for logic, but a blank first frame is unacceptable for screens.

Passing viewModelScope.coroutineContext as the context is a tip that can eliminate whole classes of memory-leak and stale-update bugs, but it's easy to miss because the default is an empty context.

Concepts & terms
CoroutineLiveData
The engine behind the liveData builder and asLiveData: an internal MediatorLiveData subclass that owns a coroutine scope, a BlockRunner, and the suspend block to run. It starts the block when observers become active and schedules cancellation when they leave.
BlockRunner
The dispatcher inside CoroutineLiveData that manages the running collect coroutine and the delayed cancellation coroutine. It implements the 5-second default grace period that lets rotation-style brief inactivations keep the same collect stream alive.
SupervisorJob (in this context)
A job that isolates the collect coroutine from the caller-supplied context. Cancelling the LiveData on inactive won't propagate up to viewModelScope, because the SupervisorJob acts as a layer that absorbs cancellation without failing the parent.
From the discussion
Featured comments
booboosui

A consequence you only run into on a physical device: the 5 seconds are counted from when the last observer leaves, and on return it doesn't continue collecting—the whole block runs from scratch. BlockRunner.maybeRun() starts a new coroutine each time to invoke(block), and runningJob is non-null only while active observers remain. So for a cold flow like flow { emit(load()) }, switching to the background and coming back after more than 5 seconds triggers another request; the logs show two starts. To avoid it, stateIn the upstream into viewModelScope and forward it, at the cost of losing the automatic timeout-convergence mechanism and having to manage cancellation yourself.

hai_android

flow { emit(load()) } is a cold flow with no state sharing; returning from the background causes a re-request. asLiveData() internally uses the liveData {} builder. When the LiveData observer count changes from 0 to 1, it starts a coroutine to collect the upstream Flow; when the observer count drops to zero, it cancels that coroutine. stateIn turns a cold flow into a hot flow; stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null) achieves state sharing to avoid duplicate requests while preserving the "no re-request when returning within 5 seconds of backgrounding" effect.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗