用RxJava链接改装调用

时间:2015-11-20 09:58:51

标签: android retrofit rx-java

所以基本上我要做的就是进行第一次网络通话。如果被调用的RESTful Web服务返回1,则进行第二次网络调用。如果Web服务返回0,则不进行第二次网络呼叫。

这是我的代码

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());

显然上面的代码是错误的,因为它应该总是返回Observable。那么,如果第一个网络调用返回0,我的代码应该怎么写?

1 个答案:

答案 0 :(得分:1)

我认为最佳做法是返回Observable.error(new Throwable("..."))

取自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>
     */