Search code examples
androidandroid-workmanager

CoroutineWorker: interrupt doWork() on cancelPendingIntent action


Is it possible to cancel the work done in doWork() when the cancel action from the notification is triggered?

class TestWorker(context: Context, parameters: WorkerParameters) :
    CoroutineWorker(context, parameters) {

    override suspend fun doWork(): Result {

        setForeground(createForegroundInfo())
        doStuff()
        return Result.success()
    }

    private fun doStuff() {
        for (i in 0..10) {
            Log.d(LOG, "Can this be interrupted?")
            Thread.sleep(1000)
        }
    }

    private fun createForegroundInfo(): ForegroundInfo {
        val cancelIntent = WorkManager.getInstance(applicationContext)
            .createCancelPendingIntent(id)

        val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)

            ...

            .addAction(android.R.drawable.ic_delete, "cancel", cancelIntent)
            .build()

        createChannelIfNeeded()
        return ForegroundInfo(1, notification)
    }


Solution

  • Thread.sleep(1000) is not interruptible by Coroutines. If you use delay(1000), then it will be interruptible as per this blog post.

    private suspend fun doStuff() {
        for (i in 0..10) {
            Log.d(LOG, "Can this be interrupted?")
            delay(1000)
        }
    }