Search code examples
androidandroid-jetpackandroid-workmanager

CoroutineWorker crashing when using WorkManager#enqueueUniqueWork but not when using WorkManager#enqueue


I'm using Android Jetpacks's WorkManager. I defined a fairly standard CoroutineWorker doing network and DB processing but I can't uniquely enqueue it using WorkManager#enqueueUniqueWork.

I always end up with a

Work [ id=****, tags={ **** } ] was cancelled

But if I use WorkManager#enqueue, the very same work request runs perfectly.

I'm a bit clueless here. I tried to search for a similar problem elsewhere but my DDG-fu has failed me. I fear that this is tied to a coroutine problem but I'm not confortable enough with them to know where to search...


Solution

  • This is expected. As per the ExistingWorkPolicy.REPLACE Javadoc:

    If there is existing pending (uncompleted) work with the same unique name, cancel and delete it. Then, insert the newly-specified work.

    Therefore it is expected that any work that uses that same unique name will be cancelled. This is true for any type of work - a Worker will get a callback to onStopped() which is the sign that it needs to cooperatively cancel itself.

    Coroutines support cancellation by default, so your CoroutineWorker handles cancellation automatically.