Fallback Observable for RxJava

前端 未结 6 1428
-上瘾入骨i
-上瘾入骨i 2021-02-02 00:25

I\'m in search for a better way to achieve a simple Observable fallback system for empty results when using RxJava. The idea is that, if a local query for a set of data results

6条回答
  •  北海茫月
    2021-02-02 01:13

    I'm sure there's more elegant solution to this problem but you could simply use flatMap in this case. Since you're already dealing the List which is returned from queryLocalDatabase() method you could do something like this.

    Observable.create(new Observable.OnSubscribe>() {
        @Override
        public void call(Subscriber> subscriber) {
            List results = queryLocalDatabase();
            subscriber.onNext(results);
            subscriber.onCompleted();
        }
    
        private List queryLocalDatabase() {
            return Arrays.asList();
        }
    
    }).flatMap(new Func1, Observable>() {
        @Override
        public Observable call(List list) {
            if (list.isEmpty()) {
                return getFallbackObservable();
            } else {
                return Observable.from(list);
            }
        }
    
        private Observable getFallbackObservable() {
            return Observable.from("3", "4");
        }
    
    }).subscribe(new Observer() {
        @Override
        public void onCompleted() {
            System.out.println("onCompleted");
        }
    
        @Override
        public void onError(Throwable e) {
            System.out.println("onError");
        }
    
        @Override
        public void onNext(String s) {
            System.out.println("onNext: " + s);
        }
    });
    

    I've replace Object for String for the purpose of this code.

    提交回复
    热议问题