通过改造和rxjava链接请求

时间:2016-11-29 14:01:58

标签: android rx-java

我需要制作大约5个链接请求,例如我有5个不同的调用,我想让它们按特定顺序串行不平行。

以下是我的观察能力的一些例子

Observable<ResponseBody> textsCall=EndpointFactory.provideEndpoint().getTexts(textsTask.getLanguage())
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread());

Observable<AirportCombo> routesCall=EndpointFactory.provideEndpoint().getRoutes()
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread());

实际上,我不知道rx java上有什么功能。

早先我已经实现了并行请求,现在我需要串行。

如果您需要并行方法,请:

Observable<ResponseResult> combined = Observable.zip(textsCall, routesCall, (textsBody, airportCombo) -> {
            //some parsing and other logic
            return new ResponseResult(flag);
        });

1 个答案:

答案 0 :(得分:8)

您可以将flatmap功能用于此目的

textsCall
 .flatMap(new Func1 < ResponseBody, Observable < AirportCombo >> () {
  @Override
  public Observable < AirportCombo > call(ResponseBody valueA) {
   // code to save data from service valueA to db
   // call service B
   return routesCall;
  }
 })
 .flatMap(new Func1 < AirportCombo, Observable < ValueC >> () {
  @Override
  public Observable < ValueC > call(AirportCombo valueB) {
   // code to save data from service valueB to db
   // call service C
   return observableC;
  }
 })
 .flatMap(new Func1 < ValueC, Observable < ValueD >> () {
  @Override
  public Observable < ValueD > call(ValueC valueC) {
   // code to save data from service valueC to db
   // call service D
   return observableD;
  }
 })
 .flatMap(new Func1 < ValueD, Observable < ValueFinal >> () {
  @Override
  public Observable < ValueFinal > call(ValueD valueC) {
   // code to save data from service valueD to db
   // call Final Service
   return observableFinal;
  }
 })
 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(new Subscriber < ValueFinal > () {
  @Override
  public void onCompleted() {}

  @Override
  public void onError(Throwable e) {

  }

  @Override
  public void onNext(ValueFinal fooB) {
   // code to save data from service ValueFinal to db

  }
 });