问题描述
我正在使用改造,我觉得rxjava(带有retrolambda)将非常适合以下流程:
I'm using retrofit and I feel like rxjava (with retrolambda) would be a good fit for the following flow:
- 获取小部件列表(http)
-
每个小部件
- get list of widgets (http)
for each widget
a)获取给定窗口小部件类型的文章(http)列表
b)将所有这些保存到db
c)获取列表中的第一(最新)文章,并使用本文中的适当值更新widget.articleName和widget.articleUrl
a) get a list of articles (http) for the given widget type
b) save all those to db
c) take the first (latest) article in list and update widget.articleName and widget.articleUrl with appropriate values from this article
但是,我不确定在执行步骤2a之后该怎么做.到目前为止,这是我的代码
However I'm unsure what to do after step 2a. Here's my code so far
apiService.getWidgets(token)
.flatMapIterable(widgets -> widgets)
.flatMap(widget -> apiService.getArticles(token, widget.type))
...
.toList()
.subscribe(
modifiedWidgets -> saveWidgets(modifiedWidgets),
throwable -> processWidgetError(throwable)
);
我曾经和一些运营商打过交道,但是在链接时,我似乎总是会缩小范围距离太远(例如处理单篇文章),然后就无法再访问原始小部件进行修改.
I've played around with some operators but when chaining, I always seem to narrow down too far (e.g. get a handle on a single article) and then no longer have access to the original widget to make modifications.
@GET("/widgets")
Observable<List<Widget>> getWidgets(@Header("Authorization") String token);
@GET("/articles")
Observable<List<Article>> getArticles(@Header("Authorization") String token, @Query("type") String type);
推荐答案
您可以在流的某些点插入doOnNext来添加副作用:
You could insert doOnNext at certain points of the stream to add side-effects:
apiService.getWidgets(token)
.flatMapIterable(v -> v)
.flatMap(w ->
apiService.getArticles(token, w.type)
.flatMapIterable(a -> a)
.doOnNext(a -> db.insert(a))
.doOnNext(a -> {
w.articleName = a.name;
w.articleUrl = a.url;
})
.takeLast(1)
.map(a -> w)
)
.toList()
.subscribe(
modifiedWidgets -> saveWidgets(modifiedWidgets),
throwable -> processWidgetError(throwable)
);
这是可运行的示例.
这篇关于使用RxJava和Retrofit遍历列表并根据子查询扩展结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!