Combination of RxJava and RxAndroid?

好久不见. 提交于 2019-12-08 07:42:49

问题


My Scenario is very similar to this Image:

Flow of the app will be like this:

  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.

So, I am updating the view twice(One from local file and just after that through webservices)

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

  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)?

What would be the good approach?


回答1:


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())
  );
}

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).

Link to the post: https://medium.com/@murki/chaining-multiple-sources-with-rxjava-20eb6850e5d9




回答2:


Looks like concat or merge operator is what you are looking for

The difference between them is:

Merge may interleave the items emitted by the merged Observables (a similar operator, Concat, does not interleave items, but emits all of each source Observable’s items in turn before beginning to emit items from the next source Observable).

Observable retroFitBackendObservable = retrofitBackend.getFoo().doOnNext(save_it_into_local_file );
Observable mergedObservable =  Observable.merge(cacheObservable, retroFitBackendObservable);
mergedObservable.subscribe( ... );

Then subscribe for mergedObservable and update your view in onNext()



来源:https://stackoverflow.com/questions/36182269/combination-of-rxjava-and-rxandroid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!