download

Why does this Android coroutine keep running after leaving the screen?

Mobile~8 minReviewed 2 Dec 2026Free · No sign-in

Question

A stock-ticker screen collects prices and polls every 5 seconds:

"KOTLIN"
// Inside TickerActivity.onCreate:
lifecycleScope.launch {
    viewModel.priceStream.collect { render(it) }
}

// Inside TickerViewModel:
fun startPolling() = viewModelScope.launch {
    while (true) {
        try {
            refreshQuotes()
            delay(5_000)
        } catch (e: Exception) {
            logError(e)
        }
    }
}

When you press Home, render(it) keeps firing in the background. When you leave the screen and viewModelScope cancels, startPolling() still loops forever.

  1. Explain why both bugs happen.
  2. Fix both with structured concurrency.
Show hints (3)
  1. "WHEN THE SCOPE CANCELS"

    lifecycleScope stays alive while the Activity is STOPPED in the background. It cancels only on ON_DESTROY.

  2. "CHECK EXCEPTION HIERARCHY"

    delay(5_000) signals cancellation by throwing CancellationException, which is a subclass of Exception. What does catch (e: Exception) do to it?

  3. "RETHROW AND REPEAT"

    Wrap flow collection in repeatOnLifecycle(Lifecycle.State.STARTED). In startPolling(), rethrow CancellationException before catching other exceptions.

Show checked explanation

lifecycleScope.launch cancels only at ON_DESTROY, so collecting directly keeps running while the app is STOPPED. Wrap collection in repeatOnLifecycle(Lifecycle.State.STARTED) (or collectAsStateWithLifecycle() in Compose). Inside startPolling(), catch (e: Exception) swallows CancellationException thrown by delay(5_000), breaking cooperative cancellation. Rethrow CancellationException before logging failures.

Lifecycle transitions, flow collection cancellation, and CancellationException handling were checked in a Python 3.12 concurrency model against Jetpack Lifecycle 2.8 and Kotlin Coroutines 1.9 documentation. Checked by an editor other than the author.

Walkthrough

Structured concurrency ties each coroutine's lifetime to a parent scope, so cancelling the parent cancels every child. Both bugs break that link in different ways.

scope or APIcancels atcommon pitfall
GlobalScopenever (process death)leaks screens, sockets, and memory
viewModelScopeViewModel.onCleared()stays alive during backgrounding unless stopped
lifecycleScope.launchON_DESTROYcollects flows while UI is STOPPED
repeatOnLifecycle(STARTED)ON_STOP (restarts at ON_START)must use viewLifecycleOwner in Fragments

In the first bug, pressing Home moves TickerActivity to ON_STOP, not ON_DESTROY. The collect coroutine never cancels, so render(it) keeps touching hidden views and holding upstream producers active. repeatOnLifecycle(Lifecycle.State.STARTED) cancels the collection block on ON_STOP and launches a fresh collector on ON_START.

In the second bug, Kotlin cancellation is cooperative. When viewModelScope cancels, delay(5_000) throws CancellationException. Because CancellationException extends IllegalStateException, which extends Exception, the broad catch (e: Exception) catches it, logs it, and lets while (true) loop forever.

"KOTLIN"
// UI: cancel collection on ON_STOP, restart on ON_START
lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.priceStream.collect { render(it) }
    }
}

// ViewModel: never swallow CancellationException
fun startPolling() = viewModelScope.launch {
    while (isActive) {
        try {
            refreshQuotes()
            delay(5_000)
        } catch (e: CancellationException) {
            throw e
        } catch (e: Exception) {
            logError(e)
        }
    }
}

Checking while (isActive) (or calling ensureActive() inside CPU loops) ensures cancellation stops work even before the next suspending call.

Common mistakes

  • Catching Exception or Throwable in a coroutine without rethrowing CancellationException, silently preventing cancellation from stopping the job.
  • Using GlobalScope.launch for screen work, which detaches the coroutine from structured concurrency and leaks it until process death.
  • Using lifecycleScope instead of viewLifecycleOwner.lifecycleScope in a Fragment, which leaks duplicate collectors when the view recreates.
  • Running a heavy non-suspending loop without ensureActive() or yield(), because cancelled coroutines only exit at cooperative checkpoints.

Follow-up questions

  • "Why was launchWhenStarted deprecated in favor of repeatOnLifecycle?" launchWhenStarted only paused the coroutine when the lifecycle dropped below STARTED. The upstream flow stayed subscribed in the background, wasting battery and network connections. repeatOnLifecycle cancels collection on ON_STOP and restarts it on ON_START.
  • "How do you avoid restarting a network stream on a fast screen rotation?" Share the upstream flow in the ViewModel with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial). The 5,000 ms grace period bridges quick rotation, yet stops the producer if the app stays backgrounded.
  • "What goes wrong if you pass a fresh Job() into viewModelScope.launch(Job())?" Passing a new Job() overrides the parent job and breaks structured concurrency. Cancelling viewModelScope can no longer reach that child coroutine, so it leaks until it finishes on its own.

What a strong answer covers

Contrasts lifecycleScope with repeatOnLifecycle(STARTED), explains why catch (e: Exception) swallows CancellationException, rethrows it, and mentions viewLifecycleOwner or WhileSubscribed(5_000).

Open in interactive practice deck →

Original OfferVibe question. Kotlin coroutines on Android · StateFlow and SharedFlow · Kotlin cancellation and timeouts.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.