I am super new to Rx stuff and wish to improve my knowledge.
The following code works fine, however I want to know how can I improve it. There are two Single observables (mSdkLocationProvider.lastKnownLocation()
and mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude())
). Second observable depends on first observable's result.
I know there are some ops such as zip, concat, concatMap, flatMap. I read about all of them and I am confused now :)
private void loadAvailableServiceTypes(final Booking booking) {
final Location[] currentLocation = new Location[1];
mSdkLocationProvider.lastKnownLocation()
.subscribe(new Consumer<Location>() {
@Override
public void accept(Location location) throws Exception {
currentLocation[0] = location;
}
}, RxUtils.onErrorDefault());
mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ServiceTypeResponse>() {
@Override
public void accept(ServiceTypeResponse serviceTypeResponse) throws Exception {
onServiceTypesReceived(serviceTypeResponse.getServiceTypeList());
}
}, new CancellationConsumer() {
@Override
public void accept(Exception e) throws Exception {
Logger.logCaughtException(TAG, e);
}
});
}
flatMap is generally the operator to use when you the second operation depends on the result of the first. flatMap works like an inline subscriber. For your example above you could write something like:
mSdkLocationProvider.lastKnownLocation()
.flatMap(currentLocation -> {
mPassengerAPI.getServiceType(currentLocation[0].getLatitude(), currentLocation[0].getLongitude())
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(...)
You can use the same subscriber you had above, it will have the results of getServiceType.