{"id":1036,"date":"2026-11-19T13:47:00","date_gmt":"2026-11-19T12:47:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=1036"},"modified":"2026-11-18T19:07:00","modified_gmt":"2026-11-18T18:07:00","slug":"code-after-collect-never-runs","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/code-after-collect-never-runs\/","title":{"rendered":"Code After collect Never Runs: Why a Second StateFlow collect Is Never Called"},"content":{"rendered":"<p>Code after collect never runs because <code>collect<\/code> is a suspend call that returns only when its flow completes. A <code>StateFlow<\/code> or <code>SharedFlow<\/code> never completes. So a second <code>collect<\/code> placed below the first one in the same coroutine is never called. Nothing crashes and nothing logs. The first flow keeps rendering. The second one is dead code. This often appears after a refactor. A one-shot <code>flow { emit(...) }<\/code> completes after one value, so the line below it used to run. Swap it for a <code>stateIn<\/code> flow and that line stops running. The fix is one coroutine per flow. Inside <code>repeatOnLifecycle<\/code>, wrap each <code>collect<\/code> in its own <code>launch<\/code>. Android&#8217;s own sample does this. In an interview, name both causes. The suspension alone is harmless with a cold flow that finishes. The hot flow alone is harmless when it is the only collector.<\/p>\n\n<h2>The unread badge froze when the order screen moved to stateIn<\/h2>\n\n<p>An order-tracking screen shows the order status and an unread-messages badge. The first version loaded the order once. Then the team made the status live, so it now updates from Packed to Shipped. Here is the Fragment code. It didn&#8217;t change in the refactor.<\/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=\"\">class OrderFragment : Fragment(R.layout.fragment_order) {\n    private val viewModel: OrderViewModel by viewModels()\n\n    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n        super.onViewCreated(view, savedInstanceState)\n        viewLifecycleOwner.lifecycleScope.launch {\n            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {\n                viewModel.order.collect { renderOrder(it) }\n                viewModel.unreadCount.collect { badge.text = it.toString() }\n            }\n        }\n    }\n}\n\nclass OrderViewModel(repo: OrderRepository) : ViewModel() {\n    \/\/ Before: val order: Flow&lt;Order&gt; = flow { emit(repo.fetchOrder(\"A17\")) }\n    val order: StateFlow&lt;Order&gt; = repo.observeOrder(\"A17\")\n        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), Order(\"A17\", \"Loading\"))\n\n    val unreadCount: StateFlow&lt;Int&gt; = repo.unreadCount\n}<\/pre>\n\n\n<p>The Android pieces can&#8217;t compile outside an Android project. So we rebuilt the same shape in plain Kotlin. A small <code>whileStarted<\/code> function stands in for <code>repeatOnLifecycle<\/code> and runs the block in a child scope. Two <code>MutableStateFlow<\/code> objects stand in for the repository. The script ran both ViewModel versions. Each run pushed two messages and one status change. It used Kotlin 2.4.20 and kotlinx.coroutines 1.10.2 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=\"\">before refactor: render order Packed\nbefore refactor: badge = 0\nbefore refactor: badge = 1\nbefore refactor: badge = 2\nbefore refactor: unread is really 2\n---\nafter refactor: render order Loading\nafter refactor: render order Packed\nafter refactor: render order Shipped\nafter refactor: unread is really 2<\/pre>\n\n\n<p>Before the refactor, the badge counted every message. The status never moved past Packed. That is why the team made it live. After the refactor, the status updates correctly. The badge line never prints at all. The ViewModel holds 2 unread messages. The screen shows none of them. Two rules stack to cause this.<\/p>\n\n<h2>Code after collect never runs until the flow completes<\/h2>\n\n<p><code>collect<\/code> is a suspend function. It runs your lambda for each value. It returns to the caller only when the upstream flow finishes. Until then, the coroutine that called it is parked inside it.<\/p>\n\n<p>So the two lines in the block are sequential. The second <code>collect<\/code> starts only after the first one returns. Android&#8217;s <a href=\"https:\/\/developer.android.com\/topic\/libraries\/architecture\/views\/coroutines-views\" target=\"_blank\" rel=\"noopener\">guide to lifecycle-aware coroutines in Views<\/a> says this in a code comment. Because <code>collect<\/code> suspends, collecting several flows in parallel needs different coroutines. Its multi-flow sample wraps each <code>collect<\/code> in its own <code>launch<\/code>.<\/p>\n\n<p>This rule alone did no harm before the refactor. The old <code>order<\/code> flow was <code>flow { emit(repo.fetchOrder(\"A17\")) }<\/code>. That builder completes after its single <code>emit<\/code>. So the first <code>collect<\/code> returned after one value. Then the badge collector started. The output shows it. The status rendered once as Packed, then the badge counted to 2.<\/p>\n\n<h2>A StateFlow never completes, so the badge collector never starts<\/h2>\n\n<p>The refactor also changed the first flow&#8217;s type. 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> has a section titled &#8220;State flow never completes.&#8221; It says a <code>collect<\/code> on a state flow &#8220;never completes normally.&#8221; 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> says the same about shared flows. <code>stateIn<\/code> returns a <code>StateFlow<\/code>, so <code>order<\/code> is now a flow that never ends.<\/p>\n\n<p>Put the two rules together. The first <code>collect<\/code> waits for completion. Completion never comes. The coroutine stays parked on line one for as long as the screen is started. Then <code>repeatOnLifecycle<\/code> cancels the block when the screen stops. That cancellation also skips the badge line. When the user comes back, the block restarts and parks on line one again. The badge never gets a turn.<\/p>\n\n<p>Nothing in the build flags this. The compiler sees two valid suspend calls. The order status looks fine on screen. A reviewer reading the diff only sees a ViewModel change, because the Fragment didn&#8217;t change.<\/p>\n\n<h2>Give each flow its own launch inside repeatOnLifecycle<\/h2>\n\n<p>Each <code>collect<\/code> needs its own coroutine. Start them with <code>launch<\/code> inside the <code>repeatOnLifecycle<\/code> block. That matches the multi-flow sample in the <a href=\"https:\/\/developer.android.com\/topic\/libraries\/architecture\/views\/coroutines-views\" target=\"_blank\" rel=\"noopener\">Views coroutines guide<\/a>.<\/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=\"\">viewLifecycleOwner.lifecycleScope.launch {\n    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {\n        launch { viewModel.order.collect { renderOrder(it) } }\n        launch { viewModel.unreadCount.collect { badge.text = it.toString() } }\n    }\n}<\/pre>\n\n\n<p>Both launches are children of the <code>repeatOnLifecycle<\/code> block. So both stop when the screen stops. Both restart when it starts again. The plain-Kotlin version of this fix printed both streams, interleaved.<\/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: render order Loading\nfixed: badge = 0\nfixed: render order Packed\nfixed: badge = 1\nfixed: render order Shipped\nfixed: badge = 2\nfixed: unread is really 2<\/pre>\n\n\n<p><code>flow.onEach { ... }.launchIn(this)<\/code> inside the block works too. The <a href=\"https:\/\/kotlinlang.org\/api\/kotlinx.coroutines\/kotlinx-coroutines-core\/kotlinx.coroutines.flow\/launch-in.html\" target=\"_blank\" rel=\"noopener\"><code>launchIn<\/code> reference<\/a> calls it a shorthand for <code>scope.launch { flow.collect() }<\/code>. The other option is a single UI state. The ViewModel combines order and unread count into one <code>StateFlow<\/code>. The Fragment collects that one flow. That changes the design, so mention it as a follow-up. Our post on <a href=\"https:\/\/grindloop.ai\/blog\/kotlin-flow-combine-not-emitting\/\">why combine can stop emitting<\/a> covers what goes wrong in that version.<\/p>\n\n<h2>The interview answer starts from the badge that never updates<\/h2>\n\n<p>In a debugging round you usually get the symptom, not the cause. Here the symptom is that the badge stays empty while the status updates. Walk from that symptom to both rules.<\/p>\n\n<ol>\n<li>Note that the badge lambda never runs at all. It doesn&#8217;t show a stale value. So the problem is the collector, not the data.<\/li>\n<li>Point at the two <code>collect<\/code> calls in one block. They run one after the other.<\/li>\n<li>Name the first cause. <code>collect<\/code> suspends until its flow completes.<\/li>\n<li>Name the second cause. <code>order<\/code> comes from <code>stateIn<\/code>. A <code>StateFlow<\/code> never completes.<\/li>\n<li>Explain why it worked before. The old <code>flow { emit(...) }<\/code> completed after one value.<\/li>\n<li>Give the fix. Wrap each <code>collect<\/code> in its own <code>launch<\/code> inside <code>repeatOnLifecycle<\/code>.<\/li>\n<\/ol>\n\n<p>Step 5 shows you know the bug came from a change in flow type. That means you would also check other screens that collect the refactored flow. Hass covers how the debugging 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>Rewrites that still leave the badge frozen<\/h2>\n\n<p>&#8220;Use <code>collectLatest<\/code>.&#8221; It cancels the previous lambda when a new value arrives. It still suspends until the flow completes. Our run with <code>collectLatest<\/code> printed all three statuses and no badge line.<\/p>\n\n<p>&#8220;Swap the two lines.&#8221; Now the badge collects first and never returns. Our run printed the badge 0, 1 and 2. It printed no order status at all. The bug moves to the other flow.<\/p>\n\n<p>&#8220;Read the order with <code>first()<\/code>, then collect the badge.&#8221; The badge works. The order is worse. <code>first()<\/code> took the <code>stateIn<\/code> initial value, so our run rendered Loading and stopped there. The status never reached Packed or Shipped.<\/p>\n\n<p>&#8220;Wrap the first <code>collect<\/code> in <code>withContext(Dispatchers.IO)<\/code>.&#8221; Changing threads doesn&#8217;t change suspension. <code>withContext<\/code> returns only when its block returns. Our run printed the three statuses and no badge, same as the original.<\/p>\n\n<p>&#8220;Put the badge <code>collect<\/code> after <code>repeatOnLifecycle<\/code>.&#8221; The <a href=\"https:\/\/developer.android.com\/reference\/kotlin\/androidx\/lifecycle\/package-summary\" target=\"_blank\" rel=\"noopener\"><code>repeatOnLifecycle<\/code> reference<\/a> says it suspends the caller until the lifecycle is <code>DESTROYED<\/code>. So that line runs only as the view is torn down.<\/p>\n\n<p>&#8220;Call <code>launchIn(lifecycleScope)<\/code> outside <code>repeatOnLifecycle<\/code>.&#8221; This one does update the badge. But it collects while the screen is in the background. Android&#8217;s <a href=\"https:\/\/developer.android.com\/kotlin\/flow\/stateflow-and-sharedflow\" target=\"_blank\" rel=\"noopener\">StateFlow and SharedFlow guide<\/a> warns against collecting UI flows straight from <code>launch<\/code> or <code>launchIn<\/code>. Keep the extra coroutines inside the lifecycle-aware block.<\/p>","protected":false},"excerpt":{"rendered":"<p>Code after collect never runs because a StateFlow never completes, so a second collect is never called. Runnable repro, the launch fix and the wrong answers.<\/p>\n","protected":false},"author":2,"featured_media":1037,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"Code After collect Never Runs: Why a Second StateFlow collect Is Never Called","rank_math_description":"Code after collect never runs because a StateFlow never completes, so a second collect is never called. Runnable repro, the launch fix and the wrong answers.","rank_math_focus_keyword":"code after collect never runs","footnotes":""},"categories":[9,3],"tags":[15,13,87,16,12,110,32,14,45],"class_list":["post-1036","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-coroutines","tag-android","tag-coroutines","tag-debugging-interview","tag-interview-prep","tag-kotlin","tag-kotlin-flow","tag-lifecycle","tag-stateflow","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1036","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=1036"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1036\/revisions"}],"predecessor-version":[{"id":1038,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/1036\/revisions\/1038"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/1037"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=1036"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=1036"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=1036"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}