我正在尝试实现 Android ListenableWorker
startWork()
method 返回 com.google.common.util.concurrent.ListenableFuture
接口,但最后一个不可用。我还需要 com.google.common.util.concurrent.SettableFuture
实施,但这也是不可用的。我应该包含哪个模块才能使这些类型可用?
app.gradle
...
dependencies {
...
implementation "androidx.work:work-runtime-ktx:2.1.0"
}
MyWorker.kt
class SendRegistrationTokenWorker(
context: Context,
params: WorkerParameters,
) : ListenableWorker(context, params) {
override fun startWork(): ListenableFuture<Result> { ... }
}
据我了解,我想要的依赖项是
com.google.guava:listenablefuture:1.0
,但是 androidx.work:work-runtime-ktx:2.1.0
已经依赖于它,以及应用程序使用的其他库。问题是 com.google.guava:listenablefuture:1.0
解析为 com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava
,它不包含所需的类型,它只是一个模拟依赖项。
我尝试添加单独的
com.google.guava:listenablefuture:1.0
依赖项,但它也解析为 com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava
并且没有任何变化。
如果我强制将
listenablefuture
版本设置为 1.0
,则会收到错误:
程序类型已存在: com.google.common.util.concurrent.ListenableFuture
android {
...
configurations.all {
resolutionStrategy {
force "com.google.guava:listenablefuture:1.0"
}
}
}
...
最后,我发现的最简单的解决方案是将整个番石榴依赖项添加到项目中。我不确定这是正确的方法,因为我只使用库中的几种类型。但是,这是我正在寻找的简单解决方案。
build.gradle
dependencies {
...
implementation 'com.google.guava:guava:28.0-android'
}
我还在 ListenableWorker 中找到了 Threading 关于 ListenableWorker 实现的 Android 文档部分,建议使用 councurrent-futures CallbackToFutureAdapter(如果应用程序不使用 guava)。我尝试了一下,但是解决方案没有解决错误,
ListenableFuture
没有找到。
另一个解决方案是,如果您使用的是 Kotlin,则切换并扩展
CoroutineWorker
,因为 Kotlin 具有不需要这些 guava
依赖项的挂起函数 API,并且返回类型只是一个 Result
对象。有关更多详细信息,请查看 Google 文档。