The Android Developer Challenge is back! Submit your idea before December 2.

Unique work

Unique work is a powerful concept that guarantees that you only have one chain of work with a particular name at a time. Unlike ids, unique names are human-readable and specified by the developer instead being auto-generated by WorkManager. Unlike tags, unique names are only associated with one chain of work.

You can create a unique work sequence by calling WorkManager.enqueueUniqueWork(String, ExistingWorkPolicy, OneTimeWorkRequest) or WorkManager.enqueueUniquePeriodicWork(String, ExistingPeriodicWorkPolicy, PeriodicWorkRequest). The first argument is the unique name - this is the key we use to identify the WorkRequests. The second argument is the conflict resolution policy, which specifies what WorkManager should do if there's already an unfinished chain of work with that unique name:

  • Cancel the existing chain and REPLACE it with the new one.
  • KEEP the existing sequence and ignore your new request.
  • APPEND your new sequence to the existing one, running the new sequence's first task after the existing sequence's last task finishes. You cannot use APPEND with PeriodicWorkRequests.

Unique work can be useful if you have a task that shouldn't be enqueued multiple times. For example, if your app needs to sync its data to the network, you might enqueue a sequence named "sync", and specify that your new task should be ignored if there's already a sequence with that name. Unique work sequences can also be useful if you need to gradually build up a long chain of tasks. For example, a photo editing app might let users undo a long chain of actions. Each of those undo operations might take a while, but they have to be performed in the correct order. In this case, the app could create an "undo" chain and append each undo operation to the chain as needed.

Finally, if you need to create a chain of unique work, you can use WorkManager.beginUniqueWork(String, ExistingWorkPolicy, OneTimeWorkRequest) instead of beginWith().