{"id":984,"date":"2026-11-11T13:47:00","date_gmt":"2026-11-11T12:47:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=984"},"modified":"2026-11-10T18:19:14","modified_gmt":"2026-11-10T17:19:14","slug":"kotlin-flow-combine-not-emitting","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/kotlin-flow-combine-not-emitting\/","title":{"rendered":"Kotlin Flow combine Not Emitting: Why a MutableSharedFlow Input Leaves Your StateFlow on Loading"},"content":{"rendered":"<p>A Kotlin Flow combine not emitting anything means one of its inputs has never produced a value. The <code>combine<\/code> operator emits nothing until every input flow has emitted at least once. So a single silent input keeps the whole result silent. A <code>MutableSharedFlow<\/code> created with no arguments is the usual silent input. It has no replay cache and no buffer. A <code>tryEmit<\/code> call with no subscribers returns <code>true<\/code> and drops the value. A <code>tryEmit<\/code> call with a subscriber returns <code>false<\/code> and also drops it. Neither call throws. The screen sits on its <code>stateIn<\/code> initial value, usually a Loading state. No log explains why. The fix is to hold the input as state. Use <code>MutableStateFlow<\/code> with an initial value. Write to it with <code>value =<\/code>. Then <code>combine<\/code> has a value from the first collection. It also keeps the latest value across a <code>WhileSubscribed<\/code> restart.<\/p>\n\n<h2>Kotlin Flow combine not emitting leaves a checkout screen on Loading<\/h2>\n\n<p>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 <code>MutableSharedFlow<\/code>.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">data class Coupon(val code: String, val percentOff: Int)\ndata class Cart(val subtotalCents: Long)\n\nsealed interface CheckoutUi {\n    data object Loading : CheckoutUi\n    data class Ready(val totalCents: Long, val coupon: Coupon?) : CheckoutUi\n}\n\nclass CheckoutViewModel(scope: CoroutineScope, cart: Flow&lt;Cart&gt;, savedCoupon: Coupon?) {\n    private val selectedCoupon = MutableSharedFlow&lt;Coupon?&gt;()\n\n    val ui: StateFlow&lt;CheckoutUi&gt; =\n        combine(cart, selectedCoupon) { c, coupon -&gt;\n            val off = c.subtotalCents * (coupon?.percentOff ?: 0) \/ 100\n            CheckoutUi.Ready(c.subtotalCents - off, coupon)\n        }.stateIn(scope, SharingStarted.WhileSubscribed(5_000), CheckoutUi.Loading)\n\n    init {\n        selectedCoupon.tryEmit(savedCoupon)\n    }\n\n    fun applyCoupon(c: Coupon) {\n        selectedCoupon.tryEmit(c)\n    }\n}<\/pre>\n\n\n<p>In the app, <code>scope<\/code> is <code>viewModelScope<\/code> and the cart is a Room flow. Our repro used a plain <code>CoroutineScope<\/code> and a <code>MutableStateFlow&lt;Cart&gt;<\/code> instead. A screen coroutine collected <code>ui<\/code>. Then we called <code>applyCoupon<\/code>. We logged each <code>tryEmit<\/code> result and the subscriber count. It ran with Kotlin 2.4.20 and kotlinx.coroutines 1.11.0 on OpenJDK 25.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">init tryEmit returned true, subscribers=0\nscreen: Loading\nafter 300 ms: Loading\napplyCoupon tryEmit returned false, subscribers=1\nafter applyCoupon: Loading<\/pre>\n\n\n<p>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.<\/p>\n\n<h2>combine waits for a first value from every input<\/h2>\n\n<p>The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/combine.html\" target=\"_blank\" rel=\"noopener\"><code>combine<\/code> reference<\/a> says it combines the most recently emitted value of each flow. Its example output starts only after both flows have emitted. The reference doesn&#8217;t state the waiting rule in plain words. The source does.<\/p>\n\n<p>We traced <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/blob\/master\/kotlinx-coroutines-core\/common\/src\/flow\/internal\/Combine.kt\" target=\"_blank\" rel=\"noopener\"><code>combineInternal<\/code> in kotlinx.coroutines<\/a>. It fills a slot array with an <code>UNINITIALIZED<\/code> marker. A counter called <code>remainingAbsentValues<\/code> 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.<\/p>\n\n<p>So the cart&#8217;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 <code>stateIn<\/code> keeps its initial value of <code>Loading<\/code>.<\/p>\n\n<p>That rule is fine for inputs that always have a value. A Room query emits its current rows on collection. A <code>StateFlow<\/code> emits its current value. A plain <code>MutableSharedFlow<\/code> emits nothing to a new subscriber.<\/p>\n\n<h2>A default MutableSharedFlow drops every tryEmit<\/h2>\n\n<p><code>MutableSharedFlow()<\/code> with no arguments means <code>replay = 0<\/code> and <code>extraBufferCapacity = 0<\/code>. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/-mutable-shared-flow.html\" target=\"_blank\" rel=\"noopener\">factory function reference<\/a> lists both defaults. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/-shared-flow\/\" target=\"_blank\" rel=\"noopener\"><code>SharedFlow<\/code> reference<\/a> spells out what follows. On such a flow, <code>tryEmit<\/code> succeeds &#8220;only if there are no subscribers.&#8221; In that case, the reference adds, the value &#8220;is immediately lost.&#8221;<\/p>\n\n<p>Both coupon writes fall into that rule. They fail in opposite ways.<\/p>\n\n<p>The <code>init<\/code> call runs before anything collects. <code>WhileSubscribed<\/code> doesn&#8217;t start <code>combine<\/code> until the screen subscribes. So the coupon flow has no subscribers yet. In <a href=\"https:\/\/github.com\/Kotlin\/kotlinx.coroutines\/blob\/master\/kotlinx-coroutines-core\/common\/src\/flow\/SharedFlow.kt\" target=\"_blank\" rel=\"noopener\">the <code>SharedFlow<\/code> source<\/a>, <code>tryEmitNoCollectorsLocked<\/code> handles this case. With <code>replay == 0<\/code> it returns <code>true<\/code> and keeps nothing. The saved coupon is gone. The call still reported success.<\/p>\n\n<p>The <code>applyCoupon<\/code> call runs while the screen collects. Now <code>combine<\/code> has a subscriber on the coupon flow. A buffer of zero means an <code>emit<\/code> would have to suspend until that subscriber takes the value. <code>tryEmit<\/code> can&#8217;t suspend, so it returns <code>false<\/code>. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/-mutable-shared-flow\/try-emit.html\" target=\"_blank\" rel=\"noopener\"><code>tryEmit<\/code> reference<\/a> says <code>false<\/code> is possible only with <code>SUSPEND<\/code> overflow and active subscribers. The code ignores the return value, so this coupon is gone too.<\/p>\n\n<p>Put the two causes together. <code>combine<\/code> needs one coupon value. The coupon flow can&#8217;t deliver one. Either cause alone would show up quickly. A <code>StateFlow<\/code> input would satisfy <code>combine<\/code>. A buffered flow fed through <code>emit<\/code> would deliver the user&#8217;s coupon. The checkout ViewModel uses a plain shared flow and <code>tryEmit<\/code>, so both rules bite.<\/p>\n\n<h2>Hold the coupon in a MutableStateFlow<\/h2>\n\n<p>A selected coupon is state. It has a current value at every moment. That value may be <code>null<\/code>. So it belongs in a <code>StateFlow<\/code>. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/-state-flow\/\" target=\"_blank\" rel=\"noopener\"><code>StateFlow<\/code> reference<\/a> says a state flow always has an initial value. It replays the latest value to each new subscriber.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fun price(c: Cart, coupon: Coupon?): CheckoutUi {\n    val off = c.subtotalCents * (coupon?.percentOff ?: 0) \/ 100\n    return CheckoutUi.Ready(c.subtotalCents - off, coupon)\n}\n\nclass CheckoutViewModel(scope: CoroutineScope, cart: Flow&lt;Cart&gt;, savedCoupon: Coupon?) {\n    private val selectedCoupon = MutableStateFlow(savedCoupon)\n\n    val ui: StateFlow&lt;CheckoutUi&gt; = combine(cart, selectedCoupon, ::price)\n        .stateIn(scope, SharingStarted.WhileSubscribed(5_000), CheckoutUi.Loading)\n\n    fun applyCoupon(c: Coupon) {\n        selectedCoupon.value = c\n    }\n}<\/pre>\n\n\n<p>The <code>init<\/code> block is gone. The saved coupon is the initial value, so nothing can drop it. A <code>value<\/code> 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 <code>WhileSubscribed<\/code> to 200 ms so it would finish quickly.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">fixed, first visit: Ready(totalCents=8000, coupon=Coupon(code=FALL20, percentOff=20))\nfixed, apply SAVE10: Ready(totalCents=9000, coupon=Coupon(code=SAVE10, percentOff=10))\nfixed, back after timeout: Ready(totalCents=9000, coupon=Coupon(code=SAVE10, percentOff=10))<\/pre>\n\n\n<p>The saved 20% coupon shows on the first visit. The applied coupon replaces it. It survives the upstream stop and restart. The <code>StateFlow<\/code> lives in the ViewModel, outside the shared pipeline. Android&#8217;s <a href=\"https:\/\/developer.android.com\/kotlin\/flow\/stateflow-and-sharedflow\" target=\"_blank\" rel=\"noopener\">StateFlow and SharedFlow guide<\/a> makes the same split. A <code>StateFlow<\/code> needs an initial state. A <code>SharedFlow<\/code> is the configurable general case, with <code>replay<\/code> as one of its knobs.<\/p>\n\n<p>Keep a <code>SharedFlow<\/code> for a real one-off signal like a snackbar. Even then, don&#8217;t feed it into <code>combine<\/code>. An event has no &#8220;current value&#8221; for <code>combine<\/code> to pair with the cart. One-off events have their own delivery traps. We cover those in <a href=\"https:\/\/grindloop.ai\/blog\/one-time-events-jetpack-compose-keep-breaking\/\">why one-time events in Compose keep breaking<\/a>.<\/p>\n\n<h2>How to answer when the interviewer only says &#8220;the screen is stuck&#8221;<\/h2>\n\n<p>In a debugging round you often get the symptom first. Here it&#8217;s a checkout screen that never leaves its spinner. Work from the output back to both causes.<\/p>\n\n<ol>\n<li>Find which <code>StateFlow<\/code> value the screen shows. It&#8217;s <code>Loading<\/code>, the <code>stateIn<\/code> initial value. So the <code>combine<\/code> lambda never ran.<\/li>\n<li>Log each input with <code>onEach<\/code>. The cart logs a value. The coupon flow logs nothing.<\/li>\n<li>Name the first cause. <code>combine<\/code> runs its transform only after every input has emitted once.<\/li>\n<li>Name the second cause. A default <code>MutableSharedFlow<\/code> has no replay and no buffer. <code>tryEmit<\/code> drops the value with no subscribers and returns <code>false<\/code> with one.<\/li>\n<li>Point out the ignored <code>Boolean<\/code>. Nothing checks <code>tryEmit<\/code>, so both drops are silent.<\/li>\n<li>Give the fix. The coupon is state, so use <code>MutableStateFlow(savedCoupon)<\/code> and set <code>value<\/code>.<\/li>\n<\/ol>\n\n<p>Say step 2 out loud. The interviewer hears you test the hypothesis before you change code. The same <code>combine<\/code> plus <code>stateIn<\/code> pipeline can also go stale for a different reason. See <a href=\"https:\/\/grindloop.ai\/blog\/why-your-combined-stateflow-shows-stale-data-sharingstarted-lazily-vs-eagerly\/\">why a combined StateFlow shows stale data<\/a>. Hass explains how the bug-squash round is scored in <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">finding the bug and still not passing<\/a>.<\/p>\n\n<h2>Three patches that look right and still lose the coupon<\/h2>\n\n<p>&#8220;Call <code>emit<\/code> from a launched coroutine instead of <code>tryEmit<\/code>.&#8221; We ran <code>scope.launch { selectedCoupon.emit(savedCoupon) }<\/code> in <code>init<\/code>. The first visit still showed <code>Loading<\/code>. The <code>SharedFlow<\/code> reference says <code>emit<\/code> on this flow returns at once when there are no subscribers. So the value is lost the same way, only a moment later.<\/p>\n\n<p>&#8220;Seed it with <code>onStart { emit(null) }<\/code>.&#8221; This gets <code>combine<\/code> 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 <code>init<\/code> 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 <code>onStart<\/code> again. The shared flow had no replay to restore SAVE10.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">onStart, first visit: Ready(totalCents=10000, coupon=null)\nonStart, apply SAVE10: Ready(totalCents=9000, coupon=Coupon(code=SAVE10, percentOff=10))\nonStart, back after timeout: Ready(totalCents=10000, coupon=null)<\/pre>\n\n\n<p>&#8220;Switch the input to <code>MutableSharedFlow(replay = 1)<\/code>.&#8221; This one does fix our checkout. One replay slot keeps the last coupon for late subscribers. It also gives <code>tryEmit<\/code> room to succeed. But it is a <code>StateFlow<\/code> with parts missing. It has no <code>value<\/code> to read and no initial value. If some code path skips the <code>init<\/code> emit, <code>combine<\/code> stalls again. <code>MutableStateFlow<\/code> can&#8217;t be created without a value, so that path can&#8217;t exist.<\/p>","protected":false},"excerpt":{"rendered":"<p>Kotlin Flow combine not emitting? It waits for every input, and a default MutableSharedFlow drops each tryEmit. Runnable repro, StateFlow fix, wrong answers.<\/p>\n","protected":false},"author":2,"featured_media":986,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"Kotlin Flow combine Not Emitting: MutableSharedFlow Leaves StateFlow on Loading","rank_math_description":"Kotlin Flow combine not emitting? It waits for every input, and a default MutableSharedFlow drops each tryEmit. Runnable repro, StateFlow fix, wrong answers.","rank_math_focus_keyword":"kotlin flow combine not emitting","footnotes":""},"categories":[9,3],"tags":[15,13,16,12,110,69,14,45],"class_list":["post-984","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-coroutines","tag-android","tag-coroutines","tag-interview-prep","tag-kotlin","tag-kotlin-flow","tag-sharedflow","tag-stateflow","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/984","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=984"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/984\/revisions"}],"predecessor-version":[{"id":985,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/984\/revisions\/985"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/986"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=984"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=984"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=984"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}