Fallback Observable for RxJava

前端 未结 6 1435
-上瘾入骨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条回答
  •  猫巷女王i
    2021-02-02 01:08

    Use switchIfEmpty operator.

    There is example of usage:

    Observable.create(new Observable.OnSubscribe() {
        @Override
        public void call(Subscriber subscriber) {
            // return no item
            //subscriber.onNext(...);
            System.out.println("Generating nothing :)");
            subscriber.onCompleted();
        }
    }).switchIfEmpty(Observable.create(new Observable.OnSubscribe() {
        @Override
        public void call(Subscriber subscriber) {
            System.out.println("Generating item");
            subscriber.onNext("item");
            subscriber.onCompleted();
        }
    })).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);
        }
    });
    

    Simplified with lamdas:

    Observable.create(subscriber -> {
        // return no item
        //subscriber.onNext(...);
        System.out.println("Generating nothing :)");
        subscriber.onCompleted();
    }).switchIfEmpty(Observable.create(subscriber -> {
        System.out.println("Generating item");
        subscriber.onNext("item");
        subscriber.onCompleted();
    })).subscribe(
        s -> System.out.println("onNext: " + s),
        throwable -> System.out.println("onError"),
        () -> System.out.println("onCompleted")
    );
    

提交回复
热议问题