Unique Work

Sometimes, we want to avoid accidentally enqueuing the same work more than once.

For example, suppose that the app has a Worker that pulls data from a server. Normally, that is triggered by a push message (e.g., Firebase Cloud Messaging). However, you also have it set up that user actions can trigger that work to be done, such as via a manual refresh option (e.g., pull-to-refresh). What you want to avoid is trying to do two of this bit of work simultaneously, as that might confuse things on either the device side or the server side.

To handle this, instead of enqueue() on WorkManager, you can use beginUniqueWork(). This takes a “name” that identifies this logical unit of work. If you previously used beginUniqueWork(), and you later call beginUniqueWork() with the same name, and the earlier work is still ongoing, you can specify what should happen (e.g., ignore the new work request).

Note that this does not support periodic work: you can only coordinate OneTimeWorkRequest, not PeriodicWorkRequest.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.