skip to content

As Android lead, what rule do you set for which work goes to WorkManager, which stays in a coroutine, and which becomes a user-visible transfer?

level: principalimportance: should knowfreq 32%

answer

  1. must it outlive the screen?
  2. deferrable vs exact vs watched
  3. foreground costs and quotas
  4. unique names, idempotent workers

basics

~20 s

Work that must finish after the user leaves goes to WorkManager as unique, idempotent requests; work only the open screen needs stays in a scoped coroutine. Long transfers the user watches use setForeground, or a platform user-initiated transfer under quota pressure.

solid answer

~50 s

My rule starts with one question: does this have to finish if the user leaves now? If not, it stays in a ViewModel coroutine and is cancelled with the screen. If yes, it goes to WorkManager, enqueued as unique work, with workers that are idempotent, pass IDs rather than payloads in `Data`, and report through `WorkInfo`. Within WorkManager, short user-triggered work is expedited with `RUN_AS_NON_EXPEDITED_WORK_REQUEST`, and long work the user is watching uses `setForeground()` with the right service type. Everything else is constrained deferrable work. The costs I accept are that WorkManager never promises an exact time, that foreground workers carry Android 14 type rules and, from Android 16, eat into job quotas, and that on-demand initialization can delay rescheduling after a crash. A big user-started download may justify the platform's user-initiated transfer job instead.

go deeper

for a junior

Recall the core split: screen work in coroutines, work that must finish after the user leaves in WorkManager.

for a middle

Explain how expedited, long-running and deferrable work map to different WorkManager APIs and what each guarantees.

for a senior

Turn the split into reviewable conventions: unique names, idempotent workers, ID-only Data, WorkInfo-driven UI and stop-reason logging.

for a principal

Own the trade-offs: exact-time requests renegotiated, foreground quota costs from Android 14 and 16, on-demand initialization vs recovery, and when a transfer should leave WorkManager.

## The question behind the rule Teams misuse WorkManager in two opposite ways. Some send everything through it, including a search request a screen needs within a second, and then wonder why results arrive late or after the user has left. Others keep critical uploads in an application-scoped coroutine and lose them every time the process dies. A lead's job is a rule simple enough that every pull request can be checked against it: > **Does this work have to finish even if the user leaves the app right now?** - **No:** it belongs to the screen. Run it in a coroutine scoped to the ViewModel or lifecycle, so it is cancelled with the screen. Coroutines themselves are their own lesson; the point here is that WorkManager is the wrong tool. - **Yes:** it belongs to WorkManager, which persists the request, survives process death and reboot, and respects constraints. ## A decision table the team can apply | Work | Where it goes | Why | |---|---|---| | Loading data for the visible screen | screen-scoped coroutine | the result is useless once the screen is gone | | Sending a message or one photo the user just took | WorkManager, `setExpedited(RUN_AS_NON_EXPEDITED_WORK_REQUEST)` | must finish, should start now, takes seconds | | Backing up a whole album the user started | WorkManager with `setForeground()` and a `dataSync` `ForegroundInfo` | long, user-visible, may exceed ten minutes | | Nightly cleanup, sync or log upload | constrained `PeriodicWorkRequest` with `ExistingPeriodicWorkPolicy.UPDATE` | deferrable; cheapest for battery | | An alarm the user set for 07:00 | not WorkManager | WorkManager never promises an exact time | ## What the rule costs - **No exact timing.** WorkManager guarantees execution, not the moment. Product requirements phrased as "every 5 minutes" or "at 9:00 sharp" need renegotiating, because periodic work has a 15-minute floor and runs when the OS allows. - **Foreground workers are not free.** Apps targeting Android 14 must declare a foreground service type for every long-running worker. Service types carry platform time limits; WorkManager 2.10 added `STOP_REASON_FOREGROUND_SERVICE_TIMEOUT` to report them. From Android 16, long-running workers, still scheduled through `JobScheduler`, can **exhaust the app's job quota**. For those cases the documentation suggests starting a foreground service directly, or, for a download the user asked for, a user-initiated data transfer job, which is exempt from the ordinary job quotas. That is the point where a transfer may leave WorkManager. - **Expedited work is rationed.** Its quota depends on the app's standby bucket and process importance, so a rarely used app typically gets less. Out of quota, `RUN_AS_NON_EXPEDITED_WORK_REQUEST` keeps the work and `DROP_WORK_REQUEST` loses it; the team default should be the former. - **Startup vs recovery.** On-demand initialization through `Configuration.Provider` takes WorkManager off the cold-start path, but its documentation warns that it may delay automatic rescheduling after a crash and recovery after a force-stop, because WorkManager is not initialized until it is first needed. An app whose background guarantees matter more than a few milliseconds of startup may keep the default initializer. ## Conventions that come with the rule 1. **Every enqueue site uses unique work**, with names in one constants file, so retries, app restarts and double taps resolve through an explicit policy instead of silently duplicating jobs. 2. **Workers are idempotent**: a run can be stopped by a lost constraint, the ten-minute limit or a quota, and then repeated. 3. **`Data` carries IDs and URIs**, never payloads; it is capped at 10 KB. 4. **Screens read `WorkInfo`** (`getWorkInfosForUniqueWorkFlow`) instead of callbacks, so state survives process death. 5. **One worker factory**, registered through `Configuration.Provider`, owns construction, and worker class names are treated as stable because enqueued work stores them. 6. **Each worker ships with a test** built with `TestListenableWorkerBuilder`, and scheduling behaviour is checked with `WorkManagerTestInitHelper` and its `TestDriver`. 7. **`WorkInfo.stopReason` is logged**, so the team can see whether quotas, constraints or timeouts are stopping work in the field. ## When to revisit the rule Revisit it when the platform moves: a new Android release that changes job quotas or foreground-service rules, a WorkManager release that adds scheduling controls such as `setNextScheduleTimeOverride` (2.9.0) or the experimental event listeners in 2.12.0, or field data showing that `STOP_REASON_QUOTA` or service timeouts dominate. The rule exists to be checked against evidence, not to be applied forever.

  • A product manager asks for a balance refresh every 5 minutes in the background; what do you answer in WorkManager terms?
    WorkManager cannot do it: `PeriodicWorkRequest` clamps any interval to at least 15 minutes, and the OS decides when within that each run happens. I'd offer a refresh when the screen opens, a 15-minute or longer periodic request with constraints, or a server push that triggers short expedited work.
  • Why might a team keep WorkManager's default initializer even though on-demand initialization speeds up cold start?
    Because the default initializer starts WorkManager with every process launch, which lets it reschedule work promptly after a crash or a force-stop. The `Configuration.Provider` documentation warns that on-demand initialization may delay those recoveries, because WorkManager is not initialized until it is first needed. If background guarantees matter more than a few milliseconds of startup, that trade can go the other way.

  • Every background task, including screen data loads, should go through WorkManager for safety.
  • An application-scoped coroutine is enough for uploads that must not be lost.
  • WorkManager can be trusted for user alarms at an exact time.
  • Foreground workers have no quota cost, so long transfers should always use setForeground.
  • On-demand initialization is strictly better than the default initializer.

Assumes WorkManager 2.12; STOP_REASON_FOREGROUND_SERVICE_TIMEOUT arrived in 2.10.0, setNextScheduleTimeOverride in 2.9.0 and the experimental event listeners in 2.12.0.