Worker 内部的同步或异步 Rxjava(来自 WorkManager 组件)什么是正确的选择? [英] Synchronous or Asynchronous Rxjava inside the Worker (from WorkManager component) what's the right choice?
问题描述
我是新架构组件 WorkManager 的新手,我通过 Retrofit 和 RxJava 调用 API.
I'm new to the new architecture component WorkManager, I do my API calls via Retrofit and RxJava.
我的用例是从后端获取新帖子,然后显示通知并更新小部件.
My use case here is to get new posts from the Backend, then show notification, and update a widget.
所以 Worker 类的 doWork() 方法中的代码可能看起来像这样.
So the code inside doWork() method from the Worker class, may look like something like this.
@NonNull
@Override
public Result doWork() {
AppDependencies appDependencies = new AppDependencies((Application) getApplicationContext());
Repository repository = appDependencies.getRepository();
repository.getNewPosts()
.flatMap(newPosts -> repository.inserPosts(newPosts).toObservable())
.doOnError(Timber::e)
//if success - > return Result.SUCCESS,
// -> show notification
// -> update widget
// error-> return Result.Failure
.dontKnowWhatBestNextThing; //blocking or subscribing
//if we reached here then Retry
return Result.RETRY;
}
我的问题是在 Worker Class 中使用 RxJava 代码的正确方法是什么,因为 doWork() 方法有返回值,所以我是否必须使 Rx 代码同步.
My Question is what is the right way to use a RxJava code inside the Worker Class because the doWork() method has a return value, so Do I have to make Rx code Synchronous.
如果我使用非阻塞 Rx 方法,我如何返回值(成功 - 失败 - 重试)
if I'm using the nonblocking Rx approach, how can I return value (Success - Failure - Retry)
推荐答案
自 WorkManager 版本 1.0.0-alpha12
起,他们添加了一个名为 work-rxjava2
的新工件,其中包括RxWorker
类正是为此目的.这是 ListenableWorker
期望 Single
的特例.
Since WorkManager version 1.0.0-alpha12
they added a new artifact called work-rxjava2
that includes RxWorker
class exactly for this purpose. It is a special case of ListenableWorker
expecting Single<Result>
.
要实现它,首先要确保在 build.gradle
中包含正确的工件:
To implement it, first make sure you include correct artifacts to your build.gradle
:
dependencies {
...
implementation "android.arch.work:work-runtime-ktx:$work_version"
implementation "android.arch.work:work-rxjava2:$work_version"
}
并实现你的RxWorker
:
class MyRxWorker(context : Context, params : WorkerParameters) : RxWorker(context, params) {
val remoteService = RemoteService()
override fun createWork(): Single<Result> {
return remoteService.getMySingleResponse()
.doOnSuccess { /* process result somehow */ }
.map { Result.success() }
.onErrorReturn { Result.failure() }
}
}
这篇关于Worker 内部的同步或异步 Rxjava(来自 WorkManager 组件)什么是正确的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!