Kotlin Flow combine Not Emitting: Why a MutableSharedFlow Input Leaves Your StateFlow on Loading

A Kotlin Flow combine not emitting anything means one of its inputs has never produced a value. The combine operator emits nothing until every input flow has emitted at least once. So a single silent input keeps the whole result silent. A MutableSharedFlow created with no arguments is the usual silent input. It has no replay cache and no buffer. A tryEmit call with no subscribers returns true and drops the value. A tryEmit call with a subscriber returns false and also drops it. Neither call throws. The screen sits on its stateIn initial value, usually a Loading state. No log explains why. The fix is to hold the input as state. Use MutableStateFlow with an initial value. Write to it with value =. Then combine has a value from the first collection. It also keeps the latest value across a WhileSubscribed restart.

Kotlin Flow combine not emitting leaves a checkout screen on Loading

A checkout ViewModel combines the cart with the coupon the user picked. The coupon arrives from two places. A saved coupon comes in at construction. The user can also apply a new one from a text field. The coupon looks like an event, so the input is a MutableSharedFlow.

data class Coupon(val code: String, val percentOff: Int)
data class Cart(val subtotalCents: Long)

sealed interface CheckoutUi {
    data object Loading : CheckoutUi
    data class Ready(val totalCents: Long, val coupon: Coupon?) : CheckoutUi
}

class CheckoutViewModel(scope: CoroutineScope, cart: Flow<Cart>, savedCoupon: Coupon?) {
    private val selectedCoupon = MutableSharedFlow<Coupon?>()

    val ui: StateFlow<CheckoutUi> =
        combine(cart, selectedCoupon) { c, coupon ->
            val off = c.subtotalCents * (coupon?.percentOff ?: 0) / 100
            CheckoutUi.Ready(c.subtotalCents - off, coupon)
        }.stateIn(scope, SharingStarted.WhileSubscribed(5_000), CheckoutUi.Loading)

    init {
        selectedCoupon.tryEmit(savedCoupon)
    }

    fun applyCoupon(c: Coupon) {
        selectedCoupon.tryEmit(c)
    }
}

In the app, scope is viewModelScope and the cart is a Room flow. Our repro used a plain CoroutineScope and a MutableStateFlow<Cart> instead. A screen coroutine collected ui. Then we called applyCoupon. We logged each tryEmit result and the subscriber count. It ran with Kotlin 2.4.20 and kotlinx.coroutines 1.11.0 on OpenJDK 25.

init tryEmit returned true, subscribers=0
screen: Loading
after 300 ms: Loading
applyCoupon tryEmit returned false, subscribers=1
after applyCoupon: Loading

The cart emitted at once. The screen still shows Loading, before and after the user applies a coupon. Two separate rules cause this. Each one alone would be easy to spot.

combine waits for a first value from every input

The combine reference says it combines the most recently emitted value of each flow. Its example output starts only after both flows have emitted. The reference doesn’t state the waiting rule in plain words. The source does.

We traced combineInternal in kotlinx.coroutines. It fills a slot array with an UNINITIALIZED marker. A counter called remainingAbsentValues starts at the number of flows. It drops by one when a slot gets its first value. The transform runs only when that counter reaches zero.

So the cart’s value sits in its slot and waits. The coupon slot still holds the marker. Until the coupon flow emits once, the lambda never runs. So stateIn keeps its initial value of Loading.

That rule is fine for inputs that always have a value. A Room query emits its current rows on collection. A StateFlow emits its current value. A plain MutableSharedFlow emits nothing to a new subscriber.

A default MutableSharedFlow drops every tryEmit

MutableSharedFlow() with no arguments means replay = 0 and extraBufferCapacity = 0. The factory function reference lists both defaults. The SharedFlow reference spells out what follows. On such a flow, tryEmit succeeds “only if there are no subscribers.” In that case, the reference adds, the value “is immediately lost.”

Both coupon writes fall into that rule. They fail in opposite ways.

The init call runs before anything collects. WhileSubscribed doesn’t start combine until the screen subscribes. So the coupon flow has no subscribers yet. In the SharedFlow source, tryEmitNoCollectorsLocked handles this case. With replay == 0 it returns true and keeps nothing. The saved coupon is gone. The call still reported success.

The applyCoupon call runs while the screen collects. Now combine has a subscriber on the coupon flow. A buffer of zero means an emit would have to suspend until that subscriber takes the value. tryEmit can’t suspend, so it returns false. The tryEmit reference says false is possible only with SUSPEND overflow and active subscribers. The code ignores the return value, so this coupon is gone too.

Put the two causes together. combine needs one coupon value. The coupon flow can’t deliver one. Either cause alone would show up quickly. A StateFlow input would satisfy combine. A buffered flow fed through emit would deliver the user’s coupon. The checkout ViewModel uses a plain shared flow and tryEmit, so both rules bite.

Hold the coupon in a MutableStateFlow

A selected coupon is state. It has a current value at every moment. That value may be null. So it belongs in a StateFlow. The StateFlow reference says a state flow always has an initial value. It replays the latest value to each new subscriber.

fun price(c: Cart, coupon: Coupon?): CheckoutUi {
    val off = c.subtotalCents * (coupon?.percentOff ?: 0) / 100
    return CheckoutUi.Ready(c.subtotalCents - off, coupon)
}

class CheckoutViewModel(scope: CoroutineScope, cart: Flow<Cart>, savedCoupon: Coupon?) {
    private val selectedCoupon = MutableStateFlow(savedCoupon)

    val ui: StateFlow<CheckoutUi> = combine(cart, selectedCoupon, ::price)
        .stateIn(scope, SharingStarted.WhileSubscribed(5_000), CheckoutUi.Loading)

    fun applyCoupon(c: Coupon) {
        selectedCoupon.value = c
    }
}

The init block is gone. The saved coupon is the initial value, so nothing can drop it. A value write never suspends and never fails. We ran three screen visits against this version. The last visit came after the screen had been gone longer than the stop timeout. The demo shortened WhileSubscribed to 200 ms so it would finish quickly.

fixed, first visit: Ready(totalCents=8000, coupon=Coupon(code=FALL20, percentOff=20))
fixed, apply SAVE10: Ready(totalCents=9000, coupon=Coupon(code=SAVE10, percentOff=10))
fixed, back after timeout: Ready(totalCents=9000, coupon=Coupon(code=SAVE10, percentOff=10))

The saved 20% coupon shows on the first visit. The applied coupon replaces it. It survives the upstream stop and restart. The StateFlow lives in the ViewModel, outside the shared pipeline. Android’s StateFlow and SharedFlow guide makes the same split. A StateFlow needs an initial state. A SharedFlow is the configurable general case, with replay as one of its knobs.

Keep a SharedFlow for a real one-off signal like a snackbar. Even then, don’t feed it into combine. An event has no “current value” for combine to pair with the cart. One-off events have their own delivery traps. We cover those in why one-time events in Compose keep breaking.

How to answer when the interviewer only says “the screen is stuck”

In a debugging round you often get the symptom first. Here it’s a checkout screen that never leaves its spinner. Work from the output back to both causes.

  1. Find which StateFlow value the screen shows. It’s Loading, the stateIn initial value. So the combine lambda never ran.
  2. Log each input with onEach. The cart logs a value. The coupon flow logs nothing.
  3. Name the first cause. combine runs its transform only after every input has emitted once.
  4. Name the second cause. A default MutableSharedFlow has no replay and no buffer. tryEmit drops the value with no subscribers and returns false with one.
  5. Point out the ignored Boolean. Nothing checks tryEmit, so both drops are silent.
  6. Give the fix. The coupon is state, so use MutableStateFlow(savedCoupon) and set value.

Say step 2 out loud. The interviewer hears you test the hypothesis before you change code. The same combine plus stateIn pipeline can also go stale for a different reason. See why a combined StateFlow shows stale data. Hass explains how the bug-squash round is scored in finding the bug and still not passing.

Three patches that look right and still lose the coupon

“Call emit from a launched coroutine instead of tryEmit.” We ran scope.launch { selectedCoupon.emit(savedCoupon) } in init. The first visit still showed Loading. The SharedFlow reference says emit on this flow returns at once when there are no subscribers. So the value is lost the same way, only a moment later.

“Seed it with onStart { emit(null) }.” This gets combine moving. The spinner goes away. But our run showed two new bugs. The first visit priced the cart at the full 10000 cents. The saved FALL20 coupon was lost, because the init emit still had no subscriber. Then the user applied SAVE10. After a visit gap longer than the stop timeout, the price reset to 10000 cents with no coupon. The restart ran onStart again. The shared flow had no replay to restore SAVE10.

onStart, first visit: Ready(totalCents=10000, coupon=null)
onStart, apply SAVE10: Ready(totalCents=9000, coupon=Coupon(code=SAVE10, percentOff=10))
onStart, back after timeout: Ready(totalCents=10000, coupon=null)

“Switch the input to MutableSharedFlow(replay = 1).” This one does fix our checkout. One replay slot keeps the last coupon for late subscribers. It also gives tryEmit room to succeed. But it is a StateFlow with parts missing. It has no value to read and no initial value. If some code path skips the init emit, combine stalls again. MutableStateFlow can’t be created without a value, so that path can’t exist.

1 thought on “Kotlin Flow combine Not Emitting: Why a MutableSharedFlow Input Leaves Your StateFlow on Loading”

Leave a Comment