我升级到WorkManager 2.1.0,并尝试使用某些Kotlin扩展,包括CoroutineWorker。我的工作人员以前在扩展androidx.work.Worker,并且通过覆盖onStopped来执行清除代码。为什么onStoppedCoroutineWorker中是最终的? CoroutineWorker停止后,还有其他方法可以执行清除代码吗?

根据this blog post,这应该是功能吗?

最佳答案

您始终可以使用job.invokeOnCompletetion,而不必依赖onStoppedCoroutineWorker回调。例如

import android.content.Context
import android.util.Log
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope

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

    companion object {
        private const val TAG = "TestWorker"
    }

    override suspend fun doWork(): Result {
        return coroutineScope {
            val job = async {
                someWork()
            }

            job.invokeOnCompletion { exception: Throwable? ->
                when(exception) {
                    is CancellationException -> {
                        Log.e(TAG, "Cleanup on completion", exception)
                        // cleanup on cancellations
                    }
                    else -> {
                        // do something else.
                    }
                }
            }

            job.await()
        }
    }

    suspend fun someWork(): Result {
        TODO()
    }
}


10-08 03:09