RxJava +改造,得到一个列表,并添加为每个项目额外的信息 [英] RxJava + retrofit, get a List and add extra info for each item
问题描述
我跟RXJava玩弄,改造中的Android。我试图完成以下任务:
I'm playing around with RXJava, retrofit in Android. I'm trying to accomplish the following:
我需要定期轮询呼叫给我一个观测>(在这里,我可以做的)
I need to poll periodically a call that give me a Observable> (From here I could did it)
一旦我得到这个名单我想遍历每个传递和调用另一个方法,这将使我的ETA(所以才更多信息)我要附加新的信息到提供和回馈的完整列表的额外连接到每个项目的信息。
Once I get this list I want to iterate in each Delivery and call another methods that will give me the ETA (so just more info) I want to attach this new info into the delivery and give back the full list with the extra information attached to each item.
我知道该怎么做,没有rxjava一旦我得到的名单,但我想练习。
I know how to do that without rxjava once I get the list, but I would like to practice.
这是我的code到目前为止:
This is my code so far:
pollDeliveries = Observable.interval(POLLING_INTERVAL, TimeUnit.SECONDS, Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR))
.map(tick -> RestClient.getInstance().getApiService().getDeliveries())
.doOnError(err -> Log.e("MPB", "Error retrieving messages" + err))
.retry()
.subscribe(deliveries -> {
MainApp.getEventBus().postSticky(deliveries);
});
这是给我发货清单。现在我想完成的第二部分。
This is giving me a list of deliveries. Now I would like to accomplish the second part.
希望我已经够清楚了。 谢谢
Hope I been enough clear. Thanks
推荐答案
最后,我找到了一个不错的方式来做到这一点。
Finally I found a nice way to do it.
private void startPolling() {
pollDeliveries = Observable.interval(POLLING_INTERVAL, TimeUnit.SECONDS, Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR))
.flatMap(tick -> getDeliveriesObs())
.doOnError(err -> Log.e("MPB", "Error retrieving messages" + err))
.retry()
.subscribe(this::parseDeliveries, Throwable::printStackTrace);
}
private Observable<List<Delivery>> getDeliveriesObs() {
return RestClient.getInstance().getApiService().getDeliveries()
.flatMap(Observable::from)
.flatMap(this::getETAForDelivery)
.toSortedList((d1, d2) -> {
if (d1.getEta() == null) {
return -1;
}
if (d2.getEta() == null) {
return 1;
}
return d1.getEta().getDuration().getValue() > d2.getEta().getDuration().getValue() ? 1 : -1;
});
}
让我们一步一步来。
Let's go step by step.
- 首先,我们创建一个可观察的触发每POLLING_INTERVAL时间的方法getDeliveriesObs()将返回最终名单
- 我们用改装来获得可观察到的通话 的
- 我们使用flatMap来flattern的resut列表,并获得在未来flatmap交货的项目,一个接一个。
- 然后,我们在抵达交付对象内部设置的估计时间和归还
- 我们对列表排序预计到达时间订购。
- 在情况下,我们打印,然后重试错误,所以间隔不停止
- 我们订阅终于得到列表进行排序,并与ETA里面,那么我们就返回它,或者任何你需要用它做。
它的正常工作,这是相当不错的,我开始喜欢rxjava:)
It's working properly and it's quite nice, I'm starting to like rxjava :)
这篇关于RxJava +改造,得到一个列表,并添加为每个项目额外的信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!