我需要在WorkManager(android.arch.work:work-runtime-ktx:1.0.0-alpha11)完成工作后回调。但是,我添加的监听器会在工作被安排后立即调用。
这是我的做法:
val work = OneTimeWorkRequestBuilder<UploadWorker>()
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 1, TimeUnit.MINUTES)
.setInputData(inputData)
.build()
workManager.beginUniqueWork(INSURANCE_UPLOAD_WORKER, ExistingWorkPolicy.REPLACE, work)
.enqueue().result.toWorkResult()
上传工作器(UploadWorker)类只有在完成整个上传序列后才会返回 Success。
以下是扩展函数的代码:
private val executor = Executor { command -> command?.run() }
class WorkResult(private val future: ListenableFuture<*>) {
fun addListener(listener: () -> Unit) {
future.addListener(Runnable {
debugLog("work result listener runnable called")
listener()
}, executor)
}
}
internal fun ListenableFuture<*>.toWorkResult(): WorkResult {
return WorkResult(this)
}
当我给WorkResult添加监听器时,它们会立即调用,而不需要等待实际工作完成。对此有何想法?