Android
WorkerTags — A Central Contract Between WorkManager Scheduler and UI Observer
String literals scattered across worker enqueue calls and UI observers are a silent refactoring hazard. A single WorkerTags object makes the contract explicit, type-safe at call sites, and audit-friendly.
- Published
- Reading
- 5 min
- Author
- Fidelis Uwem Joseph
Series · Part 2 of 8WorkManager in Production
- Injecting Dependencies into WorkManager Workers with Hilt
- WorkerTags — A Central Contract Between WorkManager Scheduler and UI Observer
- Seeding a Room Database with a WorkManager Phased Dependency Graph
- A Base Worker Template for Batched Room Inserts with Retry and Progress
- Orchestrating Android DownloadManager from a WorkManager CoroutineWorker
- Protecting Downloaded Files with a Rename-to-Backup Strategy
- Passing Structured Failure Data Out of a WorkManager Worker
- Bridging WorkManager and Compose UI via a Listener-based ProgressRepository
WorkManager identifies work by string tag. The same string appears in
addTag() when a request is built, in enqueueUniquePeriodicWork() when it
is scheduled, and in getWorkInfosByTag() when the UI observes its state.
If those strings diverge — a typo during refactoring, a copy-paste — the
work is enqueued under one name and observed under another, with no compiler
warning. A WorkerTags object collects every tag in one file and eliminates
that failure mode entirely.
Prerequisites
WorkManager 2.11.1. Familiarity with the Hilt + WorkManager setup from Part 1.
Background
The app has nine distinct workers across the download and database-seeding
pipeline. Each worker has two identifiers: an individual tag (used for
per-worker observation) and a unique work name (used for enqueueUniquePeriodicWork
deduplication). Each string can appear in up to three places in the codebase:
- In
WorkManagerUtilwhen work requests are built and enqueued - In
AcceptableProcessmethod implementations that delegate toWorkManagerUtil - In the UI layer when observing
WorkInfostate by tag
Three locations, all using the same strings, with no compile-time guarantee they match.
Implementation
1. The WorkerTags object
object WorkerTags {
// Per-worker observation tags const val DATABASE_COLORS_WORKER = "database_color_worker" const val DATABASE_CATEGORY_WORKER = "database_category_worker" const val DATABASE_GEAR_WORKER = "database_gear_worker" const val DATABASE_MINIFIGURE_WORKER = "database_minifigure_worker" const val DATABASE_PART_WORKER = "database_part_worker" const val DATABASE_CODE_WORKER = "database_code_worker" const val DATABASE_WRITE_ALL_WORKER = "database_write_all_worker" const val DOWNLOAD_INVENTORY_WORKER = "download_inventory_worker" const val DATABASE_INVENTORY_WORKER = "database_inventory_worker"
// Unique work name — used with enqueueUniquePeriodicWork / enqueueUniqueWork const val UNIQUE_WORKER_INVENTORY = "synchronization_unique_worker_inventory"}UNIQUE_WORKER_INVENTORY is the only constant here used as a unique work name
rather than a tag. The distinction matters: tags can be shared across multiple
work requests (useful for cancelling a group), while unique work names identify
a single logical operation for deduplication.
2. Using tags when building work requests
Every work request in WorkManagerUtil receives its tag from WorkerTags:
private inline fun <reified W : ListenableWorker> buildWorker(tag: String): OneTimeWorkRequest = OneTimeWorkRequestBuilder<W>() .addTag(tag) .setBackoffCriteria(BackoffPolicy.LINEAR, 1, TimeUnit.MINUTES) .build()
fun writeAllToDatabaseWithDependencies() { val colorsWork = buildWorker<WriteColorsToDatabase>(WorkerTags.DATABASE_COLORS_WORKER) val categoryWork = buildWorker<WriteCategoryToDatabase>(WorkerTags.DATABASE_CATEGORY_WORKER) val partsWork = buildWorker<WritePartsToDatabase>(WorkerTags.DATABASE_PART_WORKER) val gearWork = buildWorker<WriteGearToDatabase>(WorkerTags.DATABASE_GEAR_WORKER) val figureWork = buildWorker<WriteMinifigureToDatabase>(WorkerTags.DATABASE_MINIFIGURE_WORKER) val codesWork = buildWorker<WriteCodesToDatabase>(WorkerTags.DATABASE_CODE_WORKER)
workManager .beginWith(listOf(colorsWork, categoryWork)) .then(listOf(partsWork, gearWork, figureWork)) .then(codesWork) .enqueue()}3. Using the unique name for periodic work
fun downloadUpdate() { val request = PeriodicWorkRequestBuilder<DownloadFilesWorker>(1, TimeUnit.DAYS) .addTag(WorkerTags.DOWNLOAD_INVENTORY_WORKER) .setConstraints(networkConstraint) .build()
workManager.enqueueUniquePeriodicWork( WorkerTags.UNIQUE_WORKER_INVENTORY, // unique work name ExistingPeriodicWorkPolicy.UPDATE, request )}The request gets the DOWNLOAD_INVENTORY_WORKER tag for observation. The
unique work name UNIQUE_WORKER_INVENTORY is passed to enqueueUniquePeriodicWork
separately — that name is what prevents duplicate scheduling across app
launches.
4. Observing work state by tag from a ViewModel
val downloadWorkState: LiveData<List<WorkInfo>> = workManager.getWorkInfosByTagLiveData(WorkerTags.DOWNLOAD_INVENTORY_WORKER)
val partsWorkState: LiveData<List<WorkInfo>> = workManager.getWorkInfosByTagLiveData(WorkerTags.DATABASE_PART_WORKER)Because DOWNLOAD_INVENTORY_WORKER is the same string in the enqueue call and
the observation call, renaming it in WorkerTags updates both sites
simultaneously. There is no way to rename one without renaming the other.
5. Cancelling a group of workers
Tags also support bulk cancellation. To cancel all database-write workers without cancelling the download worker:
workManager.cancelAllWorkByTag(WorkerTags.DATABASE_PART_WORKER)workManager.cancelAllWorkByTag(WorkerTags.DATABASE_GEAR_WORKER)workManager.cancelAllWorkByTag(WorkerTags.DATABASE_MINIFIGURE_WORKER)// ...Alternatively, add a shared group tag to all database workers and cancel
by that tag. With WorkerTags as the single source of truth, adding a
group tag means adding one constant and one addTag() call per worker —
all from the same file.
Testing
./gradlew test --tests "*.WorkerTagsTest"
BUILD SUCCESSFUL in 1s1 test completedTag value tests are trivial to write but catch accidental string mutation
during merges. A snapshot test on the WorkerTags object values is a
cheap safety net.
Pitfalls
Production considerations
WorkerTags lives in extension/Constants.kt alongside URL constants and
inventory type enums. As the worker count grows, consider extracting it to
its own file and co-locating it with WorkManagerUtil in the
data/downloadmanager/ package. The test coverage benefit comes from the
constants being in a single, findable place — not from where that place is.
Wrapping up
You now have a single WorkerTags object that is the only source of truth
for every work tag and unique work name in the app. Scheduler and observer
reference the same constants, so a rename in code is mechanical and complete.
A rename of the value is a different story, covered next.
Going deeper
Tag values are persisted, so changing one is a migration. WorkManager
stores tags and unique names in its own SQLite database, and enqueued work
survives app updates. If you change the value of UNIQUE_WORKER_INVENTORY,
the next launch calls enqueueUniquePeriodicWork with a name WorkManager has
never seen, and you now have two daily downloads: the old one, still
scheduled under the old name, and the new one. Treat value changes like a
database migration: on upgrade, call cancelUniqueWork(OLD_NAME) or
cancelAllWorkByTag(OLD_TAG) once, then enqueue under the new name. Keeping
retired values in a LegacyWorkerTags object makes that cleanup explicit.
Don’t observe by class name. WorkManager automatically adds the worker’s fully qualified class name as a tag. It is tempting to observe that instead of a custom tag, but R8 renames classes in release builds and a package move changes the name. Custom string constants survive both.
Make chains unique too. beginWith(...).enqueue() creates a new chain
every time it is called. If seeding can be triggered from more than one place
(first launch, a settings button, a completed download), use
beginUniqueWork(WorkerTags.UNIQUE_SEED, ExistingWorkPolicy.KEEP, first)
so a second trigger joins the running chain instead of duplicating it.
Prefer Flow for new code. getWorkInfosByTagFlow() and
getWorkInfosForUniqueWorkFlow() return Flow<List<WorkInfo>>, which plugs
straight into a StateFlow in the ViewModel and collectAsStateWithLifecycle()
in Compose, without a LiveData bridge.