asLiveData Is a Lifecycle Bridge, Not a Data Ferry
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.
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.
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.
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.
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.