Chaining two web service calls using RxJava and Retrofit

后端 未结 1 1217
你的背包
你的背包 2021-01-06 04:52

I am using RxJava and Retrofit.My basic requirement is,i want to chain two api calls, which will get called one after one another. Response received from first api is used a

相关标签:
1条回答
  • 2021-01-06 05:29

    Consider this:

    final android.location.Address address = getAddress();
    Subscription subscription = Observable.just(address) ...
    

    This is equivalent to your code, but should also make it clear that getAddress() is evaluated before RxJava is involved and has had any chance to intervene. In other words, when you use just, the subscribeOn can only move the emission of the Address (calling onNext(address) on your Subscriber) to another thread. However, the creation of the Address - that is, your getAddress - will already have happened on the main thread when you get to this point.

    The easiest way to actually move getAddress to another thread is to use defer:

    Subscription subscription = Observable.defer(new
              Func0<Observable<android.location.Address>>() {
    
                  @Override
                  public Observable<android.location.Address> call() {
                      return Observable.just(getAddress());
                  }
              })
              .subscribeOn(Schedulers.newThread())
              .flatMap(address -> mPlatformApi.secondWebService(address.getLatitude(),address.getLongitude()    )
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(modelTwo ->
              {
                //updating My ui
              }, throwable -> {
                //Error Handling
              });
    

    This way, the whole Func0 will be executed on newThread() - not only the just but also the getAddress.

    0 讨论(0)
提交回复
热议问题