Skip to content
Commitwise
Menu

How do you make sure background work in a mobile app stops when the user leaves the screen?

AndroidMid-level

In shortStart the work in a scope tied to the screen's lifetime (viewModelScope, lifecycleScope, SwiftUI's .task), so it's cancelled automatically, and make sure the work checks for cancellation and doesn't swallow it.

Model answer

Tie the work to an owner whose lifetime matches the work:

  • Android: viewModelScope (cancelled in onCleared()), lifecycleScope with repeatOnLifecycle(STARTED) for collecting flows only while visible, and collectAsStateWithLifecycle() in Compose.
  • iOS: SwiftUI’s .task and .task(id:) (cancelled when the view disappears), structured async let and task groups, and stored Task handles cancelled in deinit or onDisappear for anything unstructured.

Cancellation is cooperative in both: it sets a flag and throws CancellationException / CancellationError at the next suspension point that checks. Networking and delay/Task.sleep check for you; long CPU loops need ensureActive() or Task.checkCancellation(). And it travels through the error path, so broad catch blocks (and Kotlin’s runCatching) must rethrow it, or the work keeps running and may show an error for a screen that’s gone.

Work that should outlive the screen (an upload the user already sent, a sync) belongs to an application-level scope, or better, to WorkManager on Android and a background URLSession or BGTaskScheduler on iOS, which also survive the process being killed.

What they're looking for

Structured concurrency on both platforms, the right scope per owner, cooperative cancellation, and the classic mistakes (GlobalScope, Task.detached, catching CancellationException). Bonus for knowing when work should outlive the screen (WorkManager, background URLSession).

Common mistakes

  • Using GlobalScope or Task.detached for screen work.
  • Catching Exception (or using runCatching) around suspend calls and swallowing cancellation.
  • Not knowing that cancellation is cooperative in CPU-heavy loops.

More android questions

Esc

Type to search the whole site.