dnocode
dnocode

Reputation: 2088

Java Rx Observable method switchIfEmpty

RxJava Lib Method switchIfEmpty the instructions inside, are always executed. Then will be evalutate if the observable is empty or not and the source or alternative will be returned. Is there a method that allows to pass just a supplier of observable that will be execute only if the source observable is empty?

As an java Optional is the same difference between

//get number from cache

private Observable<Integer> getNFromCache(){

return Observable.empty;
    }


public Observable<Integer> getNumber(){

        return getNFromCache(scope)
        .switchIfEmpty(this::doHttpRequest);

    }


private Observable<Integer> doHttoRequest(){

    return Observable.of(1);

 }

My solution

      //try to get number from cache  
public Observable<Integer> getNFromCache(){ 
    return Observable.empty;
}


private Observable<Integer> getNumber(){

 Observable<Integer> result= getNFromCache(scope);
 return !result.isEmpty().blocking().first()?result:
 result.switchIfEmpty(this::doHttpRequest);

            }


public Observable<Integer> doHttoRequest(){

   return Observable.of(1);

}

Thank you

Upvotes: 2

Views: 5278

Answers (1)

dwursteisen
dwursteisen

Reputation: 11515

There is a method that allows to pass just a supplier of observable that will be execute only if the source observable is empty?

An Observable can be see as a Supplier : it will generate your values later (ie: when you'll subscribe)

Even if the switchIfEmpty is called when you call your getNumber method, the Observable given as an argument to switchIfEmpty will only emit if you subscribe to your Observable

So, by nature, this observable will only be executed only if the source observable is empty

private Observable<Integer> getNFromCache(){
    return Observable.empty;
}


public Observable<Integer> getNumber(){
      return getNFromCache(scope)
              .switchIfEmpty(this::doHttpRequest);
}


private Observable<Integer> doHttpRequest(){
    return Observable.of(1)
                     .doOnSubscribe(() -> System.out.pritnln("START !"))
}

public static void main(String...args) {
   getNumber(); // display nothing => values are not emitted !
   getNumber().subscribe(); // display "START !"
}

Upvotes: 1

Related Questions