Code After collect Never Runs: Why a Second StateFlow collect Is Never Called

Code after collect never runs because collect is a suspend call that returns only when its flow completes. A StateFlow or SharedFlow never completes. So a second collect 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 flow { emit(...) } completes after one value, so the line below it used to run. Swap it for a stateIn flow and that line stops running. The fix is one coroutine per flow. Inside repeatOnLifecycle, wrap each collect in its own launch. Android’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.

The unread badge froze when the order screen moved to stateIn

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’t change in the refactor.

class OrderFragment : Fragment(R.layout.fragment_order) {
    private val viewModel: OrderViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.order.collect { renderOrder(it) }
                viewModel.unreadCount.collect { badge.text = it.toString() }
            }
        }
    }
}

class OrderViewModel(repo: OrderRepository) : ViewModel() {
    // Before: val order: Flow<Order> = flow { emit(repo.fetchOrder("A17")) }
    val order: StateFlow<Order> = repo.observeOrder("A17")
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), Order("A17", "Loading"))

    val unreadCount: StateFlow<Int> = repo.unreadCount
}

The Android pieces can’t compile outside an Android project. So we rebuilt the same shape in plain Kotlin. A small whileStarted function stands in for repeatOnLifecycle and runs the block in a child scope. Two MutableStateFlow 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.

before refactor: render order Packed
before refactor: badge = 0
before refactor: badge = 1
before refactor: badge = 2
before refactor: unread is really 2
---
after refactor: render order Loading
after refactor: render order Packed
after refactor: render order Shipped
after refactor: unread is really 2

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.

Code after collect never runs until the flow completes

collect 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.

So the two lines in the block are sequential. The second collect starts only after the first one returns. Android’s guide to lifecycle-aware coroutines in Views says this in a code comment. Because collect suspends, collecting several flows in parallel needs different coroutines. Its multi-flow sample wraps each collect in its own launch.

This rule alone did no harm before the refactor. The old order flow was flow { emit(repo.fetchOrder("A17")) }. That builder completes after its single emit. So the first collect 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.

A StateFlow never completes, so the badge collector never starts

The refactor also changed the first flow’s type. The StateFlow reference has a section titled “State flow never completes.” It says a collect on a state flow “never completes normally.” The SharedFlow reference says the same about shared flows. stateIn returns a StateFlow, so order is now a flow that never ends.

Put the two rules together. The first collect waits for completion. Completion never comes. The coroutine stays parked on line one for as long as the screen is started. Then repeatOnLifecycle 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.

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’t change.

Give each flow its own launch inside repeatOnLifecycle

Each collect needs its own coroutine. Start them with launch inside the repeatOnLifecycle block. That matches the multi-flow sample in the Views coroutines guide.

viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        launch { viewModel.order.collect { renderOrder(it) } }
        launch { viewModel.unreadCount.collect { badge.text = it.toString() } }
    }
}

Both launches are children of the repeatOnLifecycle 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.

fixed: render order Loading
fixed: badge = 0
fixed: render order Packed
fixed: badge = 1
fixed: render order Shipped
fixed: badge = 2
fixed: unread is really 2

flow.onEach { ... }.launchIn(this) inside the block works too. The launchIn reference calls it a shorthand for scope.launch { flow.collect() }. The other option is a single UI state. The ViewModel combines order and unread count into one StateFlow. The Fragment collects that one flow. That changes the design, so mention it as a follow-up. Our post on why combine can stop emitting covers what goes wrong in that version.

The interview answer starts from the badge that never updates

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.

  1. Note that the badge lambda never runs at all. It doesn’t show a stale value. So the problem is the collector, not the data.
  2. Point at the two collect calls in one block. They run one after the other.
  3. Name the first cause. collect suspends until its flow completes.
  4. Name the second cause. order comes from stateIn. A StateFlow never completes.
  5. Explain why it worked before. The old flow { emit(...) } completed after one value.
  6. Give the fix. Wrap each collect in its own launch inside repeatOnLifecycle.

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 finding the bug and still not passing.

Rewrites that still leave the badge frozen

“Use collectLatest.” It cancels the previous lambda when a new value arrives. It still suspends until the flow completes. Our run with collectLatest printed all three statuses and no badge line.

“Swap the two lines.” 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.

“Read the order with first(), then collect the badge.” The badge works. The order is worse. first() took the stateIn initial value, so our run rendered Loading and stopped there. The status never reached Packed or Shipped.

“Wrap the first collect in withContext(Dispatchers.IO).” Changing threads doesn’t change suspension. withContext returns only when its block returns. Our run printed the three statuses and no badge, same as the original.

“Put the badge collect after repeatOnLifecycle.” The repeatOnLifecycle reference says it suspends the caller until the lifecycle is DESTROYED. So that line runs only as the view is torn down.

“Call launchIn(lifecycleScope) outside repeatOnLifecycle.” This one does update the badge. But it collects while the screen is in the background. Android’s StateFlow and SharedFlow guide warns against collecting UI flows straight from launch or launchIn. Keep the extra coroutines inside the lifecycle-aware block.

Leave a Comment