Chaining work and constraints

Background work and notifications Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Order the steps

Order a 'compress, then upload, then clean up' chain.

  • .then(cleanup)
  • beginUniqueWork("upload-42", REPLACE, compress)
  • .then(upload) with a network constraint
  • .enqueue()

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B C A D

  1. beginUniqueWork("upload-42", REPLACE, compress) Name the chain so duplicates replace it.
  2. .then(upload) with a network constraint Only the upload needs the network.
  3. .then(cleanup) Runs only after upload succeeds.
  4. .enqueue() Nothing is scheduled until enqueue.

30-second answer

Use WorkManager.beginWith(a).then(b).then(c).enqueue(), or beginUniqueWork to name the chain. Each worker's output Data becomes the next worker's input; parallel workers' outputs are merged with an InputMerger. If one worker fails, its dependents are marked failed too. Constraints apply per request, so only the upload step may need Wi-Fi.

Practise saying it · 30 s. No recording, just a timer

Explain work chaining.

Say your answer out loud, then check which of these points you covered:

  • beginWith/then
  • Output Data feeds the next input
  • Failure stops dependents
  • Constraints per request
  • Idempotent workers

Deep dive

Observe progress with getWorkInfosForUniqueWorkFlow(name).

setProgress reports progress from a long worker to the UI.

Use tags to cancel groups of work.

Workers should be idempotent: a retry may run after a partial success.

Common mistakes

  • Doing every step in one big worker so a retry repeats everything.
  • Passing file contents as Data instead of a path or URI.
  • Non-idempotent workers that duplicate uploads on retry.

Senior take & follow-ups

Mention idempotency; retries are where real chains break.

Follow-up questions

Think of your answer first, then open the hint.

  1. What happens to the chain if step 2 fails?

    Show hint

    Step 3 and later are marked failed and don't run.

  2. How do you observe a chain in the UI?

    Show hint

    Collect getWorkInfosForUniqueWorkFlow.

Suggest a fix if something here is wrong or out of date.