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
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
.