【问题标题】:WorkManager alpha10 ListenableFuture usageWorkManager alpha10 ListenableFuture 用法
【发布时间】:2018-10-18 14:50:36
【问题描述】:

我在尝试实施最新的 WorkManager-alpha10 ListenableFuture 以处理流程完成时遇到一些问题。

现在我的 JobOrganizer 课程有以下内容

private fun enqueueDownloadWork(): ListenableFuture<Void> {
    val work = WorkManager.getInstance()
                   .beginWith(dwdTypologiesJob)
                   .then(dwdElementsJob)
                   .then(dwdAnomaliesJob)
    return work.enqueue()
}

private fun createDownloadWorkRequests() {
    dwdTypologiesJob = OneTimeWorkRequestBuilder<DWDAnomalyTypesJob>()
                .addTag("download_typologies_work")
                .build()
    dwdElementsJob = OneTimeWorkRequestBuilder<DWDElementsJob>()
                .addTag("download_elements_work")
                .build()
    dwdAnomaliesJob = OneTimeWorkRequestBuilder<DWDAnomaliesJob>()
                .addTag("download_anomalies_work")
                .build()
}

fun downloadData(): ListenableFuture<Void> {
    createDownloadWorkRequests()
    return enqueueDownloadWork()
}

这是我的电话,谁应该监听完成事件。

val listenable = JobOrganizer.downloadData()
listenable.addListener({
    Log.d("Listenable", "Did something 1");
}, {
    Log.d("Listenable", "Did something 2");
})

我仍然想念 Runnable 和 Executor 如何在这个函数上工作。谁能解释一下?

谢谢

【问题讨论】:

  • 嗨。那些听众为你工作吗?他们似乎是在我安排好工作后立即打电话给他们的。我不知道该怎么办
  • @Євген Гарастович 这可能是因为执行器会立即运行您的代码,因此在您添加侦听器之前工作已经完成。如果您查看WorkContinuationImpl 中的方法enqueue,您将看到这一点。您可以改为检查 listenable.isDone() 并根据此决定是否需要侦听器。

标签: android kotlin android-workmanager


【解决方案1】:

您需要同时实例化 Runnable 和 Executor,例如,当您想在当前线程上直接执行 Runnable 时:

.addListener(
    object:Runnable {
        override fun run() {
            Log.d("Listenable", "Did something 1");
        }
    },
    object:Executor {
        override fun execute(command: Runnable?) {
            command?.run()
        }
    }

您可以在 https://developer.android.com/reference/java/util/concurrent/Executor 上找到更多关于 Executors 的示例

【讨论】:

  • 太完美了,正是我需要的。谢谢!
【解决方案2】:

对于ListenableFutureRunnable 是您希望在完成时运行的代码,Executor 告诉它如何准确地运行该代码(例如,在哪个线程上运行它)。

这应该适用于 Kotlin:

listenableFuture.addListener(
    { /* Runnable: Code to run */ },
    { /* Executor: How to run */ }
)

一些简单的执行者可能如下:

// Run on same thread (likely to be background thread):
{ it?.run }
// Run on main thread in android:
{ Handler(Looper.getMainLooper()).post(it) }
// Run with delay on main thread in android:
{ Handler(Looper.getMainLooper()).postDelayed(it, delayMillis) }

例如,ViewModel 中的用法可能如下所示:

val dataDownloaded = MutableLiveData<Boolean>()
fun beginDownload() {
    downloadData.result.addListener(
        { dataDownloaded.postValue(true) },
        { it?.run() }
    )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2012-01-27
    • 2016-12-09
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多