Worker(来自WorkManager组件)中的同步或异步Rxjava,正确的选择是什么? [英] Synchronous or Asynchronous Rxjava inside the Worker (from WorkManager component) what's the right choice?

本文介绍了Worker(来自WorkManager组件)中的同步或异步Rxjava,正确的选择是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新架构组件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类中使用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的新工件,其中包括

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(来自WorkManager组件)中的同步或异步Rxjava,正确的选择是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆