跪拜 Guibai
← Back to the summary

asLiveData Is a Lifecycle Bridge, Not a Data Ferry

One Line of asLiveData, Behind It a Lifecycle Bridge

Author: hai_android

Tags: Android, Kotlin, Java

Based on androidx.lifecycle:lifecycle-livedata:2.7.0 source.

Bottom line first: asLiveData does not "move" the data from a Flow into LiveData. It just slots the "collect this Flow" action into a coroutine block controlled by LiveData's lifecycle. The real magic isn't in data transformation, but in "only collect when there are active observers, and delay cancellation when observers leave" — LiveData is the switch, Flow is the pipe, collect is the water flow.


1. Overview: the three layers a single call passes through

Spread out the call chain, then break it down layer by layer:

Flow.asLiveData()         <- extension function, wraps a collect
   └─ liveData { ... }     <- builder, creates a CoroutineLiveData
        └─ CoroutineLiveData : MediatorLiveData
             └─ BlockRunner → launch { execute that collect block }

Three files, three roles, each layer closer to the engine:

Layer File Role
asLiveData FlowLiveData.kt Wraps Flow into { collect { emit(it) } }
liveData CoroutineLiveData.kt Builder, returns CoroutineLiveData
CoroutineLiveData CoroutineLiveData.kt Engine: listens for lifecycle, schedules coroutines, writes data back

2. Layer one: asLiveData only does one thing

Concept: it's an extension function on Flow<T> with a surprisingly short body — hands "collect + emit" to the liveData builder, and handles the initial value of StateFlow on the side.

// FlowLiveData.kt
@JvmOverloads
public fun <T> Flow<T>.asLiveData(
    context: CoroutineContext = EmptyCoroutineContext,
    timeoutInMs: Long = DEFAULT_TIMEOUT   // default 5000ms
): LiveData<T> = liveData(context, timeoutInMs) {
    collect {          // this block won't run immediately; waits for LiveData to become active
        emit(it)       // each value from upstream is handed to LiveData
    }
}.also { liveData ->
    val flow = this
    if (flow is StateFlow<T>) {            // StateFlow has an initial value, special handling (see later)
        if (ArchTaskExecutor.getInstance().isMainThread) {
            liveData.value = flow.value    // set directly on main thread
        } else {
            liveData.postValue(flow.value) // non-main thread posts to main
        }
    }
}

Principle: note that collect { emit(it) } is a suspend lambda; at this moment it's just a "piece of code to be executed", no coroutine has been started. Who decides when it runs? Look further down.


3. Layer two: the liveData builder — creates a CoroutineLiveData

Concept: liveData is an ordinary factory with no moving logic; it directly news up a CoroutineLiveData.

// CoroutineLiveData.kt
@JvmOverloads
public fun <T> liveData(
    context: CoroutineContext = EmptyCoroutineContext,
    timeoutInMs: Long = DEFAULT_TIMEOUT,
    block: suspend LiveDataScope<T>.() -> Unit
): LiveData<T> = CoroutineLiveData(context, timeoutInMs, block)

Principle: the block here is the { collect { emit(it) } } passed in from the previous layer. It's handed over untouched to the engine. At this point, asLiveData's work is basically done — everything from here on is CoroutineLiveData's job.


4. Layer three: CoroutineLiveData — the real engine

Concept: it extends MediatorLiveData, doesn't store the Flow itself, only three things: a coroutine scope scope, an executor BlockRunner, and the block to be executed.

// CoroutineLiveData.kt (abridged, comments translated to Chinese)
internal class CoroutineLiveData<T>(
    context: CoroutineContext = EmptyCoroutineContext,
    timeoutInMs: Long = DEFAULT_TIMEOUT,
    block: Block<T>             // i.e. { collect { emit(it) } }
) : MediatorLiveData<T>() {
    private var blockRunner: BlockRunner<T>?

    init {
        // Isolate with a SupervisorJob: on inactive only cancel this run, don't touch the parent context passed in
        val supervisorJob = SupervisorJob(context[Job])
        // Runs on Main.immediate by default; caller can override via context (e.g. switch to IO)
        val scope = CoroutineScope(Dispatchers.Main.immediate + context + supervisorJob)
        blockRunner = BlockRunner(this, block, timeoutInMs, scope) {
            blockRunner = null   // after block finishes normally (or is cancelled for non-inactive reasons), executor is invalidated
        }
    }

    override fun onActive() {
        super.onActive()
        blockRunner?.maybeRun()  // observers exist → start collecting
    }

    override fun onInactive() {
        super.onInactive()
        blockRunner?.cancel()    // no one is watching → prep for cancellation
    }
}

Principle: these three lines are the foundation of the whole design.


5. Lifecycle is the switch: when collect starts and stops

Concept: BlockRunner is the "driver" inside the engine; it manages two Jobs — runningJob for the ongoing collect and cancellationJob for the delayed cancellation.

// BlockRunner (abridged, comments translated to Chinese)
internal class BlockRunner<T>(...) {
    private var runningJob: Job? = null       // the coroutine currently collecting
    private var cancellationJob: Job? = null  // delayed cancellation task

    @MainThread
    fun maybeRun() {
        cancellationJob?.cancel()   // reactivated after inactive: undo that not-yet-triggered cancellation
        cancellationJob = null
        if (runningJob != null) return        // already collecting, don't start a second one
        runningJob = scope.launch {
            val liveDataScope = LiveDataScopeImpl(liveData, coroutineContext)
            block(liveDataScope)             // ★ this is where collect actually runs
            onDone()                         // finished normally, engine invalidates
        }
    }

    @MainThread
    fun cancel() {
        cancellationJob = scope.launch(Dispatchers.Main.immediate) {
            delay(timeoutInMs)               // wait 5 seconds first
            if (!liveData.hasActiveObservers()) {  // check again that still no one is observing
                runningJob?.cancel()         // actually cancel the collect
                runningJob = null
            }
        }
    }
}

Principle: this explains two common confusions.

Why doesn't rotating the screen cause duplicate requests? When the screen rotates, the old Activity's observer briefly leaves, and onInactive triggers cancel(), but it doesn't cancel immediately — it does delay(5000). If the new Activity re-subscribes within 5 seconds, maybeRun() inside onActive first calls cancellationJob?.cancel() to revoke that cancellation, while runningJob keeps running — so collection seamlessly continues, no data is lost, no requests are repeated.

Why does data sometimes "get stuck" for 5 seconds? If the observer stays away longer than 5 seconds, the cancellation actually takes effect and runningJob gets killed; next time it becomes active, maybeRun() starts the block from scratch, and the Flow re-collects from zero. This is the root cause of the common "Flow doesn't get updates, changing timeoutInMs = 0 fixes it" posts — the timeout hit, collection was cancelled, and re-subscription restarts it.

The chain looks like this:

observe active → onActive → maybeRun → launch{ collect } → emit → setValue on main
observe leaves → onInactive → cancel → delay(5s) → still no observers → runningJob.cancel()
               ↖ reactivated within 5s → maybeRun revokes cancellation → seamless continue

6. emit: how data safely returns to the main thread

Concept: the emit(it) inside block comes from LiveDataScopeImpl, which doesn't write directly to LiveData; it first switches back to the main thread and then writes.

// LiveDataScopeImpl (abridged, comments translated to Chinese)
internal class LiveDataScopeImpl<T>(
    internal var target: CoroutineLiveData<T>,
    context: CoroutineContext
) : LiveDataScope<T> {

    // Communicates with the target LiveData using the builder's context + Main.immediate
    private val coroutineContext = context + Dispatchers.Main.immediate

    override suspend fun emit(value: T) = withContext(coroutineContext) {
        target.clearSource()   // if emitSource was called before, remove that source first
        target.value = value   // finally lands in MutableLiveData.setValue (main thread)
    }
}

Principle: withContext does two things — guarantees main-thread safety (LiveData's setValue must be on the main thread), and cooperates with cancellation (withContext is a cancellable suspension point; even if the coroutine is cancelled and emit is called, the value won't be written into LiveData. This matches the documentation's line about "values emitted by a cancelled block are ignored").


7. StateFlow's "queue jump": initial value arrives immediately

Concept: ordinary Flow is a cold stream; it has no value until you collect. StateFlow natively has value; if it also waited for active before collecting, the page would show an empty state first.

Principle: so asLiveData gives StateFlow special treatment in its .also block — it synchronizes flow.value at the moment LiveData is constructed (value on main thread, postValue on non-main). This initial value has nothing to do with lifecycle; it's just so the first screen doesn't flash empty.

val stateFlow = MutableStateFlow(0)         // initial value 0
val liveData = stateFlow.asLiveData()
// liveData.value is immediately 0, no need to wait for observe

8. Two parameters, two pitfalls

Concept: asLiveData takes only two parameters, but both deserve attention.

context: decides where collection runs. Default is EmptyCoroutineContext, ultimately grounded by Dispatchers.Main.immediate, meaning collect runs on the main thread by default. If upstream does heavy work, two correct approaches:

// Approach one: use flowOn to switch upstream to IO (recommended, clear separation)
val user = repository.flowUser(id)
    .flowOn(Dispatchers.IO)
    .asLiveData()

// Approach two: specify via context (note emit is still forced back to Main)
val user = flow.asLiveData(context = viewModelScope.coroutineContext + Dispatchers.IO)

Also, passing viewModelScope.coroutineContext has a hidden benefit: when the ViewModel is cleared, the upstream Flow cancels automatically, no need to wait for LiveData's 5-second timeout.

timeoutInMs: how long to wait after inactive before cancelling. Default 5000ms is a buffer for brief inactivations like screen rotation. Smaller → releases resources faster, fewer useless emits, but rotation is more likely to trigger re-collection; larger → more jitter-resistant, but the coroutine lives longer when no one is watching. Setting it to 0 means "cancel immediately on inactive".


9. Summary: one sentence to remember the whole chain

asLiveData wraps a Flow into a collect block and hands it to CoroutineLiveData; the latter extends MediatorLiveData and uses BlockRunner to hook "collection" onto the lifecycle — starts on active, cancels after a 5-second delay on inactive, emit always goes through the main thread; StateFlow additionally syncs an initial value.

The so-called "conversion" never transforms data, but control: it hands the timing of Flow collection over to LiveData's lifecycle.


Reference source: AndroidX lifecycle-livedata 2.7.0 — FlowLiveData.kt and CoroutineLiveData.kt.

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

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.