Android Delete a worker from WorkManager queue or change state from FAILED to CANCELLED

Viewed 1319

Component used: WorkManager

Version used: 2.3.4

Devices/Android versions reproduced on: Any

Hi There - I want to delete a worker from workmanager queue even if it has completed or is running. I know I can cancel it when Worker is in RUNNING state, the problem is when it is FINISHED and FAILED I want to delete it. Workmanager.pruneWork() deletes all workers in WorkManager but I am looking to just remove a specific one.

Here is my scenario:

  • I run a worker and it fails I return results.failure()
  • Now I have a screen which show all Workers which are in Failed state.
  • All Failed Workers I have a option to remove or Retry
  • User taps on (x) icon to remove Failed worker from UI and delete it from WorkInfoList so it doesn't show up again.
  • If there is no option to remove single Worker then how can I remove it from WorkInfoList so next time user go to that screen he doesn't see the Failed Worker that he removed?
  • Or if there is a option to change state from FAILED to CANCEL then I can just ignore cancelled ones?
  • Also after how long WorkManager automatically purge its database?

Any help will be much appreciated. Thanks.

1 Answers

I had this problem too. Both FAILED and CANCELLED are finished state, that's why the system does nothing when we try to cancel by tag, by id, etc.

As you can see here: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/states-and-observation

And here: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/managing-work#cancelling

The only way we solved this was by replacing the failed worker we want to cancel with a dummy worker. In fact, is a workaround not a solution, but it works >.< All that the dummy does is return Result.SUCCESS.

If status == FAILED
   enqueueUniqueWork(tagName, ExistingWorkPolicy.REPLACE, request)
Else
   cancelAllWorkByTag(tagName)
Related