Aashir Aashir - 5 months ago 36
Android Question

Adding condition to Observable (rx-java)

I'm still relatively new to Rx-java and reactive programming in general.

Heres my current code. What it does right now:


  1. Check device if data is present

  2. If present, fetch it

  3. If not present, fetch from server

    Observable<PastPaper> observable = Observable.concat(
    helper.loadFromDevice(params),
    helper.loadFromServer(params))
    .takeFirst(pastPaper -> pastPaper != null);

    observable.subscribe(....);



What I'm trying to accomplish:


  1. Check device if data is present

  2. If present, fetch it

  3. If not present, check if internet connection is active

  4. If internet connection is active fetch from server



How may I add the check for internet connectivity according to the steps above? (already have a method).

Any help is appreciated.
Thanks

Side question: Can my code above be improved?

Answer

You could use switchOnError so that the loadFromServer call will be ignored if it fails. For sanity's sake you might log any error from the server as a warning:

Observable<PastPaper> observable = Observable.concat(
    helper.loadFromDevice(params),
    helper.loadFromServer(params)
          .doOnError(e -> log.warn(e.getMessage()))
          .switchOnError(e -> Observable.empty())
    .takeFirst(pastPaper -> pastPaper != null);

Otherwise if you would like to use your internet connection active observable (an Observable<Boolean> say) use flatMap:

Observable<PastPaper> observable = Observable.concat(
    helper.loadFromDevice(params),
    internetAvailable
        .filter(x -> x)
        .flatMap(x -> helper.loadFromServer(params)))
    .takeFirst(pastPaper -> pastPaper != null);
Comments