Android WorkManager CoroutineWorker Detect Cancel

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.