When do you use WorkManager, a foreground service, or a coroutine in a ViewModel?
AndroidMid-level
In shortA ViewModel coroutine for work tied to a screen; WorkManager for deferrable work that must complete even if the app or device restarts, with constraints and retries; a foreground service for user-visible, ongoing work that must keep running now (playback, navigation, an active upload the user started), with a notification and a declared type.
Model answer
ViewModel coroutine (viewModelScope): work that only matters while the screen exists: loading data for the screen, debounced search. It’s cancelled when the ViewModel is cleared.
WorkManager: deferrable, guaranteed work that should survive app exits and reboots: uploading logs, syncing offline changes, refreshing caches, processing images. It supports constraints (network, charging, storage), retries with backoff, chaining, unique work, and expedited work for short urgent jobs. Periodic work runs at most every 15 minutes, and the system decides exact timing (Doze, app standby buckets).
Foreground service: work the user is aware of that must run now and continuously: music playback, turn-by-turn navigation, an ongoing call, a user-initiated large transfer. It shows a persistent notification and, since Android 14, must declare a type (mediaPlayback, location, dataSync, …) with the matching permission; Android 12+ restricts starting them from the background, and some types have time limits. For user-initiated transfers on Android 14+, consider user-initiated data transfer jobs instead.
Rule of thumb: screen-scoped → ViewModel; must happen eventually, even after restarts → WorkManager; user-visible and ongoing right now → foreground service.
What they're looking for
Clear criteria (lifetime, guarantee, user visibility, timing), WorkManager features and limits, foreground service types and restrictions in recent Android versions, and examples.
Common mistakes
- Using a foreground service for periodic syncs.
- Expecting periodic WorkManager work more often than every 15 minutes or at exact times.
- Launching long work in a coroutine scope that dies with the screen.
More android questions
- How do you make sure background work in a mobile app stops when the user leaves the screen?Mid-level
- What's the difference between a configuration change and process death on Android, and what survives each?Mid-level
- How would you modularize a large Android app, and how do you keep builds fast?Senior
- How do you store an auth token securely on Android?Mid-level