You could use Rx to chain multiple requests by using the flatMap
method.
flatMap
requires you to return another Observable
of the type of your chosing thus allowing you do something async with another type.
All of the examples below are made with the new rx v2. But all methods and mechanics also apply 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 {
// handle the exception that occurred during one of the api calls
}
})
.subscribe(new Consumer<Date>() {
@Override
public void accept(Date date) throws Exception {
// do something with the 3rd argument here
}
});
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 could apply to anything, it's not volely specific at all