Canceling Work
Frequently, the work that we enqueue into the WorkManager
is “fire and forget”, where either the work succeeds or fails on its own. Occasionally, though, we may need to try to cancel a piece of enqueued work. For example, we might offer a cancel button in the UI to allow the user to abandon some enqueued request (e.g., do not download the thing that the user just requested to download).
For that, you can call cancelWorkById()
or cancelAllWorkByTag()
on WorkManager
. The former takes the work’s ID (from getId()
on the WorkRequest
), while the latter takes a tag. Since IDs are unique, cancelWorkById()
will only try to cancel that once piece of work, while cancelAllWorkByTag()
will try to cancel all enqueued work associated with that tag. So, for example, if you associate the download
tag with your download work requests, cancelAllWorkByTag("download")
will try to cancel all of those requests.
Note, though, that cancellation is “best effort”. In particular, if the work has already begun, it might not be canceled. In some cases, this is fine. In other cases, you might want to both cancel the work in WorkManager
and take steps to ensure that any affected running work finds out about the cancellation. For example, you might have some state field somewhere that the work can monitor to see if it should continue doing whatever it is doing.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.