RxJava和RxAndroid的组合? [英] Combination of RxJava and RxAndroid?

查看:186
本文介绍了RxJava和RxAndroid的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情景与此图片非常相似:

My Scenario is very similar to this Image:

应用程序的流程如下:


  1. 查看需要更新。

  2. 使用 RxAndroid 创建一个observable来从缓存/本地文件中获取数据。

  3. 更新视图。

  4. 使用 Retrofit RxJava 进行另一次网络通话,以使用来自的新数据再次更新视图Web服务。

  5. 使用新数据更新本地文件。

  1. View needs to get updated.
  2. Create an observable using RxAndroid to fetch the data from cache / local file.
  3. update the view.
  4. Make another network call using Retrofit and RxJava to update the view again with new data coming from the web services.
  5. 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 RxAndroid ?我在想的是

How can I achieve the result using RxJava and RxAndroid? What I was thinking is


  1. 创建一个observable1来从本地文件系统获取数据。

  2. on_xt observable1 的方法中,我可以创建另一个 observable2

  3. observable2.onNext()我可以更新本地文件。
    现在如何使用更新的数据(加载到文件中)更新视图

  1. Create an observable1 to get the data from local file system.
  2. In the onNext method of observable1 I can create another observable2.
  3. observable2.onNext() I can update the local file. Now How will I update the view 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屋!

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