Why does this Android coroutine keep running after leaving the screen?
Question
A stock-ticker screen collects prices and polls every 5 seconds:
// 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.
- Explain why both bugs happen.
- Fix both with structured concurrency.
Show hints (3)
- "WHEN THE SCOPE CANCELS"
lifecycleScopestays alive while theActivityisSTOPPEDin the background. It cancels only onON_DESTROY. - "CHECK EXCEPTION HIERARCHY"
delay(5_000)signals cancellation by throwingCancellationException, which is a subclass ofException. What doescatch (e: Exception)do to it? - "RETHROW AND REPEAT"
Wrap flow collection in
repeatOnLifecycle(Lifecycle.State.STARTED). InstartPolling(), rethrowCancellationExceptionbefore 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 API | cancels at | common pitfall |
|---|---|---|
GlobalScope | never (process death) | leaks screens, sockets, and memory |
viewModelScope | ViewModel.onCleared() | stays alive during backgrounding unless stopped |
lifecycleScope.launch | ON_DESTROY | collects 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.
// 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
ExceptionorThrowablein a coroutine without rethrowingCancellationException, silently preventing cancellation from stopping the job. - Using
GlobalScope.launchfor screen work, which detaches the coroutine from structured concurrency and leaks it until process death. - Using
lifecycleScopeinstead ofviewLifecycleOwner.lifecycleScopein a Fragment, which leaks duplicate collectors when the view recreates. - Running a heavy non-suspending loop without
ensureActive()oryield(), because cancelled coroutines only exit at cooperative checkpoints.
Follow-up questions
- "Why was launchWhenStarted deprecated in favor of repeatOnLifecycle?"
launchWhenStartedonly paused the coroutine when the lifecycle dropped belowSTARTED. The upstream flow stayed subscribed in the background, wasting battery and network connections.repeatOnLifecyclecancels collection onON_STOPand restarts it onON_START. - "How do you avoid restarting a network stream on a fast screen rotation?" Share the upstream flow in the
ViewModelwithstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial). The5,000 msgrace 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. CancellingviewModelScopecan 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 →