RxJava和RxAndroid的组合? [英] Combination of RxJava and RxAndroid?
问题描述
我的情景与此图片非常相似:
My Scenario is very similar to this Image:
应用程序的流程如下:
- 查看需要更新。
- 使用
RxAndroid
创建一个observable来从缓存/本地文件中获取数据。 - 更新视图。
- 使用
Retrofit
和RxJava
进行另一次网络通话,以使用来自的新数据再次更新视图Web服务。 - 使用新数据更新本地文件。
- View needs to get updated.
- Create an observable using
RxAndroid
to fetch the data from cache / local file. - update the view.
- Make another network call using
Retrofit
andRxJava
to update the view again with new data coming from the web services. - Update the local file with the new data.
所以,我我两次更新视图(一个来自本地文件,之后就是通过webservices)
So, I am updating the view twice(One from local file and just after that through webservices)
如何使用 RxJava $ c来实现结果$ c>和
RxAndroid
?我在想的是
How can I achieve the result using RxJava
and RxAndroid
? What I was thinking is
- 创建一个observable1来从本地文件系统获取数据。
- 在
on_xt
observable1
的方法中,我可以创建另一个observable2
。 -
observable2.onNext()
我可以更新本地文件。
现在如何使用更新的数据(加载到文件中)更新视图
?
- Create an observable1 to get the data from local file system.
- In the
onNext
method ofobservable1
I can create anotherobservable2
. observable2.onNext()
I can update the local file. Now How will I update theview
with the updated data (loaded in the file)?
什么是好方法?
推荐答案
我写了一篇关于同一场景的博文。我使用了 merge 运算符(由sockeqwe建议)来解决你的积分'2'和'4'并行, doOnNext 解决'5':
I wrote a blog post about exactly this same scenario. I used the merge operator (as suggested by sockeqwe) to address your points '2' and '4' in parallel, and doOnNext to address '5':
// NetworkRepository.java
public Observable<Data> getData() {
// implementation
}
// DiskRepository.java
public Observable<Data> getData() {
// implementation
}
// DiskRepository.java
public void saveData(Data data) {
// implementation
}
// DomainService.java
public Observable<Data> getMergedData() {
return Observable.merge(
diskRepository.getData().subscribeOn(Schedulers.io()),
networkRepository.getData()
.doOnNext(new Action1<Data>() {
@Override
public void call(Data data) {
diskRepository.saveData(data); // <-- save to cache
}
}).subscribeOn(Schedulers.io())
);
}
在我的博文中,我另外使用了过滤器和时间戳如果数据相同或缓存为空,则跳过更新UI(您没有指定,但您可能也会遇到此问题)。
In my blog post I additionally used filter and Timestamp to skip updating the UI if the data is the same or if cache is empty (you didn't specify this but you will likely run into this issue as well).
链接到帖子: https:// medium .com / @ murki / chaining-multiple-sources-with-rxjava-20eb6850e5d9
这篇关于RxJava和RxAndroid的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!