workmanager侦听器立即调用 [英] workmanager listener called immediately

查看:94
本文介绍了workmanager侦听器立即调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完成工作后,我需要从WorkManager(android.arch.work:work-runtime-ktx:1.0.0-alpha11)进行回调.但是,我要添加的侦听器会在安排工作后立即被调用.

I need to have a callback upon Work completion from WorkManager (android.arch.work:work-runtime-ktx:1.0.0-alpha11). Yet the listener I'm adding is called immediately after work is scheduled.

这就是我要做的:

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类仅在完成整个上传序列后才返回成功.

The UploadWorker class returns Success only after completing the whole upload sequence.

这是扩展功能代码:

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时,将立即调用所有侦听器,而无需等待实际工作完成.有什么想法吗?

When I add listeners to WorkResult, they are all called immediately, without waiting for the actual work to complete. Any thought on this?

推荐答案

直到为此找到合适的解决方案(无GC错误等),最基本的方法是创建另一个WorkRequest并将其链接为最后的工作请求处理状态.

Until a proper solution is found for this (w/o GCed errors etc), a rudimentary approach could be to create another WorkRequest and chain it as the last work request to handle the state.

当然,您将必须分别处理错误状态(并始终为每个WorkRequest返回Result.success),以允许通过链传播.

Ofcourse, you would have to handle the error states separately (And always return Result.success for each WorkRequest) to allow propagation through the chain.

这绝不是可持续的方法,而是必要时的快速解决方案

This is by no means a sustainable approach, but rather a quick fix if necessary

这篇关于workmanager侦听器立即调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆