Callback Attorney: RESTful Volley Callback Requests? RxAndroid?

I would like to see the Java Java example of Android, how to streamline the chain of asynchronous (= non-blocking) RESTful Volley requests.

Is this what RxAndroid is used for?

  • If so, I would like to see an example using RxAndroid.
  • If not, I would still like to see a good example without diving in CALLBACK HELL!

I tried to do this, but ended up at CBHell: I need to send some volleyball requests - in sequence

I want my result from my first query to be used in the second query. Then the result of the second query, which I want to use in the third query. Please, how do I link such Volley queries?

+1
source share
1 answer

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 { // 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 may be applicable to everything; it is not explicitly specific at all.

+3
source

All Articles