skip to content

In WorkManager, how do you run compress-then-upload as one unique chain, pass Data between the steps, and observe it from the UI?

level: middleimportance: must knowfreq 62%

answer

  1. a name instead of a UUID
  2. beginUniqueWork, then, enqueue
  3. output Data becomes next input
  4. KEEP, REPLACE, APPEND, APPEND_OR_REPLACE
  5. getWorkInfosForUniqueWorkFlow

basics

~10 s

Call beginUniqueWork(name, ExistingWorkPolicy, compress).then(upload).enqueue(); each step's output Data, at most 10 KB, becomes the next step's input. Observe the chain with getWorkInfosForUniqueWorkFlow(name), which emits every step's WorkInfo.

solid answer

~40 s

I start the chain with `WorkManager.beginUniqueWork("photo-backup", policy, compress)`, add `.then(upload)` and call `enqueue()`. The compress worker returns `Result.success(workDataOf("path" to file))`, and that output becomes the upload worker's `inputData`; `Data` is capped at 10 KB, so I pass a path, never the bytes. The `ExistingWorkPolicy` decides what happens when the name is already in use: `KEEP` ignores the new chain while the old one is enqueued or running, `REPLACE` cancels and deletes it, `APPEND` hangs the new work under the old leaves but inherits a failure, and `APPEND_OR_REPLACE` starts fresh if the old work failed or was cancelled. Dependents wait in `BLOCKED`, and a failure marks every dependent `FAILED`. The UI collects `getWorkInfosForUniqueWorkFlow("photo-backup")` and reads each `WorkInfo`'s `state` and `progress`.

code

kotlin · 46 lines
kotlin
const val BACKUP_CHAIN = "photo-backup"
const val KEY_PHOTO_URI = "photo_uri"
const val KEY_COMPRESSED_PATH = "compressed_path"

class CompressWorker(appContext: Context, params: WorkerParameters) :
    CoroutineWorker(appContext, params) {
    override suspend fun doWork(): Result {
        val uri = inputData.getString(KEY_PHOTO_URI) ?: return Result.failure()
        val path = compressToCache(uri)
        return Result.success(workDataOf(KEY_COMPRESSED_PATH to path))
    }

    private fun compressToCache(uri: String): String =
        File(applicationContext.cacheDir, uri.hashCode().toString()).path
}

class UploadWorker(appContext: Context, params: WorkerParameters) :
    CoroutineWorker(appContext, params) {
    override suspend fun doWork(): Result {
        val path = inputData.getString(KEY_COMPRESSED_PATH) ?: return Result.failure()
        setProgress(workDataOf("percent" to 0))
        // Upload the file at `path`, calling setProgress as bytes are sent.
        return Result.success()
    }
}

fun enqueueBackup(context: Context, photoUri: String) {
    val compress = OneTimeWorkRequestBuilder<CompressWorker>()
        .setInputData(workDataOf(KEY_PHOTO_URI to photoUri))
        .build()
    val upload = OneTimeWorkRequestBuilder<UploadWorker>()
        .setConstraints(
            Constraints.Builder()
                .setRequiredNetworkType(NetworkType.UNMETERED)
                .build()
        )
        .build()

    WorkManager.getInstance(context)
        .beginUniqueWork(BACKUP_CHAIN, ExistingWorkPolicy.APPEND_OR_REPLACE, compress)
        .then(upload)
        .enqueue()
}

fun observeBackup(context: Context): Flow<List<WorkInfo>> =
    WorkManager.getInstance(context).getWorkInfosForUniqueWorkFlow(BACKUP_CHAIN)

go deeper

for a junior

Recall that beginWith or beginUniqueWork starts a chain, then() adds steps, and one step's output Data becomes the next step's input.

for a middle

Explain all four ExistingWorkPolicy values, the BLOCKED state, the 10 KB Data limit and how failure and cancellation propagate to dependents.

for a senior

Choose APPEND_OR_REPLACE over APPEND for user-driven queues so one failure does not poison later work, and pass URIs rather than payloads between steps.

for a principal

Standardise unique names for every enqueue site and expose chains to the UI only through WorkInfo, so screens survive process death without bespoke callbacks.

## Why the chain needs a unique name Every `WorkRequest` gets a generated `UUID`, but the screen that wants to show "backing up 3 photos" does not know those IDs after a restart, and tapping *Back up* twice would enqueue two identical chains. **Unique work** solves both: you pick a human-readable name, WorkManager allows one chain under that name at a time, and you can observe or cancel it by name. For a chain you use `beginUniqueWork(name, policy, request)`; for a single one-time request, `enqueueUniqueWork(name, policy, request)`. ## The four `ExistingWorkPolicy` values | Policy | When unfinished work already uses the name | |---|---| | `KEEP` | the new work is ignored while existing work is `ENQUEUED` or `RUNNING`; once the old work has finished, the new work is enqueued | | `REPLACE` | the existing work is cancelled (a running worker is stopped) and deleted, then the new work is inserted | | `APPEND` | the new work becomes a child of every leaf of the existing chain; if a leaf `FAILED` or was `CANCELLED`, the new work is marked the same way | | `APPEND_OR_REPLACE` | like `APPEND`, but failed or cancelled prerequisites are dropped and the new work starts a fresh chain | For a backup app that adds new photos while an upload is still running, `APPEND_OR_REPLACE` is usually right: new photos queue behind the current upload, and one failed upload does not poison every later one. ## Building the chain 1. `beginUniqueWork("photo-backup", ExistingWorkPolicy.APPEND_OR_REPLACE, compress)` returns a `WorkContinuation`. 2. `.then(upload)` adds a dependent `OneTimeWorkRequest`; every `then()` returns a new continuation. Passing a **list** to `beginWith` or `then` lets those requests run in parallel. 3. `.enqueue()` hands the whole chain to WorkManager in one operation. Only `OneTimeWorkRequest`s can be chained; periodic work cannot. ## Passing `Data` between steps - A worker returns output with `Result.success(workDataOf("path" to compressedPath))`, and that output is delivered as the **next** worker's `inputData`. - `Data` holds primitives, `String`s and arrays of them, and is limited to **10 KB serialized** (`Data.MAX_DATA_BYTES`); `Data.Builder.build()` throws `IllegalStateException` beyond that. Write large results to a file and pass its path or URI. - When several parents feed one child, an **`InputMerger`** combines their outputs. The default `OverwritingInputMerger` keeps one value per key, whichever parent wrote it last, and parallel parents finish in no guaranteed order. `ArrayCreatingInputMerger`, set with `setInputMerger(ArrayCreatingInputMerger::class.java)`, turns colliding keys into arrays. ## How failure and cancellation travel down the chain - While a prerequisite has not succeeded, its dependents sit in **`BLOCKED`**. - `Result.retry()` in one step retries just that step, with the same input; parallel branches are unaffected. - `Result.failure()` marks that request **and every dependent** `FAILED`; cancelling a request marks its dependents `CANCELLED`. - Work appended with `APPEND` to a chain that has a failed or cancelled leaf is born `FAILED` or `CANCELLED`, which is exactly why `APPEND_OR_REPLACE` exists. ## Cancelling by name `cancelUniqueWork("photo-backup")` cancels every unfinished request under the name, and their dependents are cancelled with them. A worker that is already `RUNNING` is stopped: a `CoroutineWorker`'s coroutine is cancelled, a `Worker` gets `onStopped()` and should check `isStopped`, and whatever `Result` a stopped worker returns afterwards is ignored. `REPLACE` stops a running step the same way, which is why it is the wrong policy for a queue the user keeps adding to. ## Observing from the UI Each `WorkInfo` query (by ID, tag, unique name or `WorkQuery`) comes in a `ListenableFuture`, a `LiveData` and a `Flow` form. For a unique chain the Kotlin choice is `getWorkInfosForUniqueWorkFlow(name)`, which emits a `List<WorkInfo>` (one per request) whenever any of them changes. Each `WorkInfo` carries: - `state`: `ENQUEUED`, `RUNNING`, `BLOCKED`, `SUCCEEDED`, `FAILED` or `CANCELLED`, with `state.isFinished` true for the last three; - `outputData` once a step succeeds; - `progress`, the `Data` a running worker publishes with `setProgress(workDataOf("percent" to 40))`; progress is readable only while the worker is running; - `tags`, `runAttemptCount` and, since 2.9.0, `stopReason` (readable on Android 12 and higher). A ViewModel can map that list to "compressing", "uploading 40%" or "failed, tap to retry". The Flow-returning variants were added in WorkManager 2.9.0; older code uses `getWorkInfosForUniqueWorkLiveData(name)`, which behaves the same but delivers through `LiveData`.

  • Two parallel resize workers both output a key named path; what does the upload worker receive?
    With the default `OverwritingInputMerger`, a single value: whichever parent wrote the key last wins, and parallel parents finish in no guaranteed order. To keep both, set `setInputMerger(ArrayCreatingInputMerger::class.java)` on the upload request; colliding keys then arrive as arrays.
  • When does ExistingWorkPolicy.KEEP still enqueue the new chain?
    `KEEP` ignores the new work only while existing work under the name is `ENQUEUED` or `RUNNING`. Once the earlier work has `SUCCEEDED`, `FAILED` or been `CANCELLED`, the existing records are cancelled and deleted and the new chain is enqueued as if the name were free.
  • Why not put the compressed image into the output Data of the compress step?
    `Data` is limited to 10 KB serialized, and `Data.Builder.build()` throws `IllegalStateException` past that. It also only holds primitives, strings and their arrays. Write the file to app storage and pass its path or URI; the next worker opens it.

  • APPEND keeps the new upload running even after the previous upload in that chain failed.
  • REPLACE waits for the running upload to finish before it starts the new chain.
  • Output Data can carry a compressed photo's bytes to the next worker.
  • Requests passed together as a list to beginWith always run one after another.
  • KEEP ignores the new chain even after the old one has finished.

Assumes WorkManager 2.12; the Flow-returning getWorkInfo...Flow methods and WorkInfo.stopReason exist since 2.9.0.