You can use Rx to combine multiple queries using the flatMap method.
flatMap requires that you return another Observable type of your choice, which allows you to do something asynchronous with another type.
All of the examples below are made with the new rx v2. But all methods and mechanics are also applicable to v1
Example:
final MyVolleyApi api = new MyVolleyApi(); api.getName() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMap(new Function<String, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(String name) throws Exception { return api.getAgeForName(name); } }) .flatMap(new Function<Integer, ObservableSource<Date>>() { @Override public ObservableSource<Date> apply(Integer age) throws Exception { return api.getYearOfBirthForAge(age); } }) .doOnError(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception {
This is the MyVolleyApi dummy class:
public class MyVolleyApi { public Observable<String> getName() { return Observable.just("Rx"); } public Observable<Integer> getAgeForName(String name) { return Observable.just(24); } public Observable<Date> getYearOfBirthForAge(int age) { return Observable.just(new Date()); } }
This may be applicable to everything; it is not explicitly specific at all.
source share