尝试实施最新的WorkManager-alpha10 ListenableFuture来处理流程完成时遇到一些问题。
现在,我在 JobOrganizer 类中具有以下内容
X, Y, Z = DoStuff(1,2,3)
这是我的电话,应该听完事件。
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()
}
我仍然缺少Runnable和Executor在此功能上的工作方式。有人可以解释吗?
谢谢
答案 0 :(得分:1)
例如,当您想直接在当前线程上执行Runnable时,需要实例化Runnable和Executor:
.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上找到有关执行人的更多示例
答案 1 :(得分:1)
对于ListenableFuture
,Runnable
是要在完成时运行的代码,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() }
)
}