我刚接触新的架构组件WorkManager,我使用Retrofit和RxJava进行API调用。
我的使用场景是从后端获取新的帖子,然后显示通知并更新小部件。
因此,Worker类中doWork()方法内的代码可能如下所示。
@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代码同步吗?
如果我正在使用非阻塞的Rx方法,那么如何返回值(成功-失败-重试)?
onError
或onSuccess
中使用带有大括号的lambda表达式,由于我们知道任一条件都可以工作并且可能是链接中的最后一个条件,在大括号内完成您的工作,并在最后一行将相应状态返回给WorkManager
。 - Debdeep