Android WorkManager Enqueue — Complete Guide
In this tutorial, you'll learn about Android WorkManager Enqueue. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
You enqueue a worker but it runs twice, or it doesn't run at all. You try to cancel work but the wrong task gets cancelled because you reused the same name.
Wrong Approach ❌
// Enqueueing without unique identification
WorkManager.getInstance(context)
.enqueue(OneTimeWorkRequest.from(UploadWorker::class.java))
// Same worker enqueued again from another screen
WorkManager.getInstance(context)
.enqueue(OneTimeWorkRequest.from(UploadWorker::class.java))
Output: Two identical workers running simultaneously, potentially uploading the same data twice.
Right Approach ✅
val uploadRequest = OneTimeWorkRequestBuilder<UploadWorker>()
.addTag("upload_photos")
.build()
// Use unique work for app-wide operations
WorkManager.getInstance(context)
.enqueueUniqueWork(
"upload_all_photos",
ExistingWorkPolicy.REPLACE, // KEEP, APPEND_OR_REPLACE, etc.
uploadRequest
)
// Cancelling by tag — precise
WorkManager.getInstance(context).cancelAllWorkByTag("upload_photos")
// Periodic work with unique name
val periodicRequest = PeriodicWorkRequestBuilder<SyncWorker>(15, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(context)
.enqueueUniquePeriodicWork(
"sync_schedule",
ExistingPeriodicWorkPolicy.KEEP,
periodicRequest
)
Output: No duplicate workers. Precise cancellation. Proper periodic scheduling.
Prevention
- Use
enqueueUniqueWorkwithExistingWorkPolicy.KEEPorREPLACE. - Always use descriptive tags for batch cancellation.
- Never enqueue periodic work without a unique name.
- Use
beginUniqueWorkfor chains of unique work.
Common Mistakes with workmanager enqueue
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro