CoroutineWorker: прерывание doWork () при действии cancelPendingIntent - PullRequest
1 голос
/ 27 мая 2020

Можно ли отменить работу, выполненную в doWork(), когда срабатывает действие отмены из уведомления?

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)
    }

1 Ответ

2 голосов
/ 27 мая 2020

Thread.sleep(1000) не прерывается сопрограммами. Если вы используете delay(1000), то его можно будет прервать согласно этому сообщению в блоге .

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