runCatching Swallows CancellationException: Why a Kotlin Polling Loop Freezes the App After onCleared

When runCatching swallows CancellationException, a coroutine can keep running after its scope is cancelled. A polling loop shows the worst case. You write while (true) around runCatching { fetch(); delay(5_000) } in viewModelScope. The user leaves the screen and the ViewModel is cleared. The next delay throws a CancellationException. runCatching catches it and returns a failure. The loop starts again at once. Every suspending call now throws without suspending. So the loop spins on the main thread and never lets it go. The previous screen freezes. Two causes stack here. runCatching catches every Throwable, including cancellation. A cancelled coroutine also never suspends again, so while (true) has nothing to stop it. The fix is to count a failure only while the coroutine is still active. Call ensureActive() in the catch before you wrap the error. Rethrowing every CancellationException looks simpler. But it silently ends the poller the first time a withTimeout fires.

An order-status poller that freezes the app after the screen closes

An order screen shows live delivery status. The ViewModel polls the API every few seconds. Each poll is wrapped in runCatching. A dropped connection should log a warning. Then the loop tries again.

class OrderStatusViewModel(private val api: OrderApi) : ViewModel() {
    private val _status = MutableStateFlow("loading")
    val status: StateFlow<String> = _status

    fun startPolling(orderId: String) {
        viewModelScope.launch {
            while (true) {
                runCatching {
                    _status.value = api.fetchStatus(orderId)
                    delay(500)
                }.onFailure { e ->
                    Log.w("OrderPoll", "poll failed", e)
                }
            }
        }
    }
}

We rebuilt this in plain Kotlin and ran it with Kotlin 2.4.20 and kotlinx.coroutines 1.11.0. A single-thread executor stands in for the main thread. A scope with a SupervisorJob on that thread stands in for viewModelScope. The fake API waits 100 ms and returns a status. Cancelling the scope plays the part of onCleared(). After the cancel, we posted one more task to the fake main thread. Then we waited a second for it to run.

before cancel: polls=2 failures=0
first failure: kotlinx.coroutines.JobCancellationException: Job was cancelled
1s after cancel: polls=2 failures=1908104
other main-thread work ran within 1s: false
job still active? children=1

No poll succeeds after the cancel. The failure handler still ran 1.9 million times in one second. The task we posted never ran, because the loop held the thread. The job also never finished. In the app, viewModelScope runs on Dispatchers.Main.immediate, per the AndroidX ViewModel scope source. So the screen the user went back to stops responding. Android’s ANR documentation says an ANR fires when input gets no response within 5 seconds. A real Log.w is slower than our counter, so the count would be lower. The loop still never ends.

runCatching swallows CancellationException because it catches every Throwable

runCatching is not coroutine-aware. Its source in the Kotlin standard library is a try with one catch (e: Throwable). CancellationException is a Throwable, so it becomes a Result.failure like any other error. Execution continues after the block.

Coroutines need that exception to travel up. The Kotlin cancellation guide warns that catching CancellationException can break cancellation propagation. If you must catch it, the guide says to rethrow it. Android’s coroutines best practices give the same rule. They also recommend catching specific types such as IOException over Exception or Throwable.

kotlinx.coroutines issue #1814 asks for a runCatching variant that rethrows cancellation. It was filed in February 2020 and is still open. The library still has no such function, so each team writes its own.

A cancelled coroutine never suspends again, so while (true) spins

The first cause alone would cost one extra iteration. The loop turns that into a spin. Cancellation in Kotlin is cooperative. The cancellation guide says a coroutine reacts only when it suspends or checks for cancellation explicitly. Our loop never checks. It relies on delay to stop it.

A cancelled coroutine’s delay doesn’t wait. Its KDoc in kotlinx.coroutines says a cancelled wait resumes at once with CancellationException. It also describes a prompt cancellation guarantee. In our run, a delay called after the cancel threw without waiting. The fake fetchStatus also calls delay, so it throws on entry. Each iteration now throws, gets caught and loops again. None of it suspends. The thread never comes free for other work.

So the job can’t finish either. A job completes only when its body returns. This body is a while (true) that swallows every exit. That is why the repro still showed one live child after the cancel.

Count a failure only while the coroutine is still active

Wrap the error only after a cancellation check. If the coroutine was cancelled, ensureActive() throws its CancellationException. That ends the block, the loop and the job. If the coroutine is still active, the error is a real failure, so wrap it.

suspend inline fun <T> runSuspendCatching(block: () -> T): Result<T> =
    try {
        Result.success(block())
    } catch (e: Throwable) {
        currentCoroutineContext().ensureActive()
        Result.failure(e)
    }

class OrderStatusViewModel(private val api: OrderApi) : ViewModel() {
    private val _status = MutableStateFlow("loading")
    val status: StateFlow<String> = _status

    fun startPolling(orderId: String) {
        viewModelScope.launch {
            while (true) {
                runSuspendCatching {
                    withTimeout(3_000) { api.fetchStatus(orderId) }
                }.onSuccess { _status.value = it }
                 .onFailure { e -> Log.w("OrderPoll", "poll failed", e) }
                delay(5_000)
            }
        }
    }
}

Two other changes help. delay now sits outside the catching block, so a cancelled wait always ends the loop. A withTimeout caps a hung request, so one slow poll can’t stall the rest. We ran this exact ViewModel against stubs for ViewModel and Log. One poll hung for 4 seconds and one threw IOException. Both were logged. Polling went on after each. Then we ran the first harness with this helper. After the cancel, the job had no children left. The posted task ran on the fake main thread. The handler logged no failure for the cancel.

ensureActive, normal before cancel: polls=4 failures=0 pollerAlive=true
ensureActive, normal after cancel: failures=0 children=0 mainFree=true

Rethrowing every CancellationException ends the poller on its first timeout

The common helper rethrows any CancellationException. It fixes the spin. But withTimeout signals a timeout with TimeoutCancellationException. That class is a subclass of CancellationException. The coroutine that called it is not cancelled. A rethrow-all helper still throws it out of the loop. The launch then ends quietly, because a cancellation exception never crashes. We covered that silence in our post on why withTimeout never crashes.

We made the fake API take 2 seconds and gave each poll a 300 ms timeout. Then we ran both helpers for 1.3 seconds before any cancel.

ensureActive, timeout before cancel: polls=0 failures=2 pollerAlive=true
rethrow-all, timeout before cancel: polls=0 failures=0 pollerAlive=false

The ensureActive helper logged two timeouts and kept polling. The rethrow-all helper logged nothing. Its poller was already dead. The status screen would show its last value forever with no error in the log. The ensureActive check tests whether this coroutine was cancelled. A timeout leaves the caller active, so it counts as a failed poll.

How to explain the frozen screen in a live-coding round

The round may hand you the poller and a report that the app freezes after Back. Walk from the symptom to both causes.

  1. Say the freeze starts at onCleared(). That is when viewModelScope is cancelled.
  2. Name the first cause. runCatching catches Throwable, so it turns the CancellationException into a failure.
  3. Name the second cause. A cancelled coroutine’s delay throws at once. So while (true) loops without suspending and holds the main thread.
  4. Explain why tests missed it. Nothing fails before the cancel. The cancel itself crashes nothing.
  5. Give the fix. Check ensureActive() before you wrap an error. Keep delay outside the catching block.
  6. Name the trap in the obvious fix. Rethrowing every CancellationException also rethrows a withTimeout timeout and ends the poller.

Step 6 shows you tested the fix as well as the bug. Hass covers how reviewers find planted bugs like this one in the Android code review interview. Broad catches cause a related crash in our post on viewModelScope.launch(SupervisorJob()).

Answers that leave the poller spinning or dead

“Use while (isActive).” It does stop the spin. In our run the loop exited after one more pass. But that pass logged a JobCancellationException as a failed poll. Any nested function that uses runCatching still swallows the cancel inside it.

“Catch Exception instead of Throwable.” CancellationException extends IllegalStateException, so catch (e: Exception) still catches it. kotlinx.coroutines issue #4073 calls that design error-prone. It was filed in March 2024. Our run with catch (e: Exception) spun 1.9 million times in a second.

“Check whether the failure is a CancellationException and ignore it.” Ignoring it is still swallowing it. The loop keeps going. Our version of this answer ran a million empty passes in one second. The exception has to be thrown again for the job to end.

“Run the poll on Dispatchers.IO.” The main thread comes free, so the freeze goes away. The loop does not. In our run it spun about half a million times a second on an IO thread. That burns CPU and battery until the process dies.

Leave a Comment