Jenya Kirmiza Jenya Kirmiza - 11 days ago 6
Android Question

chaining requests with retrofit and rxjava

I need to make about 5 chaining requests for example i have 5 different calls and i want to make them serial not parallel in specific order.

Here are some examples of my observables

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


Actually, i don't know what function does it on rx java.

Earlier ive implemented parallel requests, now i need serial.

If you need parallel approach here you are:

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

Answer

You can use flatmap function for this exact purpose

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

  }
 });