我如何返回一个 ListenableFuture<Result>使用工作管理器 2.0? [英] How do I return a ListenableFuture<Result> with work manager 2.0?
问题描述
ListenableWorker 似乎不再具有 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 限制,但是我无法弄清楚或找到有关如何正确返回 ListenableFuture< 的示例.Result> 在我覆盖的 startWork() 函数中.
It seems ListenableWorker no longer has the @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) restriction however I can't figure out or find examples on how to properly return a ListenableFuture< Result> in my overriden startWork() function.
据我所知,唯一的选择是返回一个 SettableFuture.create<Result>() 但这仍然需要抑制RestrictedApi"警告/错误.
As far as I can tell, the only option is to return a SettableFuture.create< Result>() but that still requires suppressing the "RestrictedApi" warning/error.
有人知道更简单的方法吗?
Anyone know a simpler way ?
据我所知,这是使用 CallbackToFutureAdapter.Completer 的方法
This is the way to do it as far as I've gathered which makes use of CallbackToFutureAdapter.Completer
override fun startWork(): ListenableFuture<Result> {
return CallbackToFutureAdapter.getFuture({
it.set(ListenableWorker.Result.success())
})
}
推荐答案
您可以通过以下两种方式之一创建 ListenableFutures:
You can create ListenableFutures one of two ways:
- 如果您使用 Guava,请使用
ListeningExecutorService
. - 否则,包括
councurrent-futures
在您的 gradle 文件中并使用CallbackToFutureAdapter
.
这篇关于我如何返回一个 ListenableFuture&lt;Result>使用工作管理器 2.0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!