Search code examples
rx-java2rx-android

RxAndroid: Create an observable which make a request and returns success/error based on response


I would like to create an Observable based on the following scenario:

  1. A request is made to the server
  2. The response then added to cache.
  3. If adding to cache is successfully only then is the success response emitted to the observer.

Thanks.


Solution

  • You can make it work this way -

    makeServerRequest()
    .subscribeOn(Schedulers.io())
    .map(someResponse -> {
         if(saveTocache()) {
             return someResponse;
         } else {
             throw new RuntimeException("Error while saving to cache");
         }
    })
    .observeOn(AndroidSchedulers.io())
    .subscribeWith(new Observer<SomeResponse> (){
        public void onError(Throwable error) {
            // here you will receive the runtime exception you throw.
        }
        :
        :
        :
    });