Android WorkManager CoroutineWorker Detect Cancel

March 3, 2020
class UploadPhotoWorker(context : Context, params : WorkerParameters) : CoroutineWorker(context, params)  {
    override suspend fun doWork(): Result {
        for (x in 1..100) {
            try {
                // do something
                delay(2000)
                // Thread.sleep(2000)
            } catch (e: CancellationException) {
                Timber.d("CancellationException")
            }

            if (isStopped) {
                Timber.d("isStopped")
                // perform cleanup/shutdown

                // this result is ignored
                return Result.success()
            }
        }

        return Result.success()
    }
}

Check isStopped within doWork().

the results of the work will be ignored by WorkManager and it is safe to stop the computation. WorkManager will retry the work at a later time if necessary.

If you are using some coroutines method such as delay, it will throw CancellationException when coroutines job cancellation happened. You might want to handle that as well to allow perform cleanup/shutdown to run.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.