Android + RxJava - loading data from db and web service

I want to use RxJava to load data from a web service (using Retrofit). I also have a database cache of previous results.

Suppose I already have observables for each of them:

Observable<List<MyModel>> networkObservable = retrofitService.getModels(); Observable<List<MyModel>> dbObservable = database.getModels(); 

I want to combine these 2 observables into one:

 public class MyModelHelper { public static Observable<List<MyModel>> getModels() { // TODO: Help! } } 

The behavior I want is for subscribers to get database results as soon as possible and then restService results when they come in (if fetching from db is faster than making a network call)

The best I could come up with myself:

 public class MyModelHelper { public static Observable<List<MyModel>> getModels() { List<MyModel> emptyList = new LinkedList<>(); // 'startWith' because combineLatest wont call back until all source observables emit something Observable.combineLatest(dbObservable.startWith(emptyList), networkObservable.startWith(emptyList), new Func2<List<MyModel>, List<MyModel>, List<MyModel>>() { @Override public List<MyModel> call(List<MyModel> first, List<MyModel> second) { return merge(first, second); } }); } } 

This seems a bit hacked to me, and I feel that there should be a better solution for such a common scenario.

It would be nice if an error occurred in the monitored network that db results would still be transmitted. I could call onErrorResumeNext() and return dbObservable itself, but I would still like subscribers to be notified that an error has occurred.

Any suggestions?

+6
source share
1 answer

Use Observable.merge directly. It combines several observable streams into one, so if the database emits faster, you will get it first.

 public static Observable<List<MyModel>> getModels() { return Observable.merge(dbObservable, networkObservable); } 
+13
source

Source: https://habr.com/ru/post/982874/


All Articles