imin
imin

Reputation: 4578

Chaining retrofit call with RxJava

So basically what I'm trying to do is, make a first network call. And if the called RESTful web service returns 1, make a second network call. If the web service returns 0, then do not make the second network call.

Here's my code

final ApiInterface apiInterface=restAdapter.create(ApiInterface.class);
apiInterface.submitDataToAnalyze("dataToAnalyze","852741963",1,"123","lalala","2015-11-20")
   .flatMap(new Func1<BasicResponse, Observable<?>>() {
    @Override
    public Observable<?> call(BasicResponse basicResponse) {
        if (basicResponse.getResult() == 1){
           return apiInterface.getSuggestion("dataToAnalyze","852741963",1,"123","lalala","2015-11-20");
         }else{
            return 0; //error
         }
  }
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());

Obviously the code above is wrong, since it should always return Observable. So how should my code be written, if the first network call returns 0?

Upvotes: 1

Views: 328

Answers (1)

Niko Adrianus Yuwono
Niko Adrianus Yuwono

Reputation: 11112

I think the best practice is to return Observable.error(new Throwable("..."))

taken from the javadoc :

/**
     * Returns an Observable that invokes an {@link Observer}'s {@link Observer#onError onError} method when the
     * Observer subscribes to it.
     * <p>
     * <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.png" alt="">
     * <dl>
     *  <dt><b>Scheduler:</b></dt>
     *  <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd>
     * </dl>
     * 
     * @param exception
     *            the particular Throwable to pass to {@link Observer#onError onError}
     * @param <T>
     *            the type of the items (ostensibly) emitted by the Observable
     * @return an Observable that invokes the {@link Observer}'s {@link Observer#onError onError} method when
     *         the Observer subscribes to it
     * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a>
     */

Upvotes: 1

Related Questions