Callback Hell: Sequencing RESTful Volley requests? RxAndroid?
Asked Answered
H

1

2

I'd like to see an Android java example of how to sequence a chain of async (= nonblocking) RESTful Volley requests.

Is this what RxAndroid is used for?

  • If so, I'd like to see the example using RxAndroid.
  • If not, I'd still like to see a good example w/out diving into CALLBACK HELL!

I tried to do so but ended up in CBHell: Need to send multiple Volley Requests - in a sequence

I want my result from my 1st request to be used in the 2nd request. Then the result from the 2nd request I want used in the 3rd request. Please, how do I chain such Volley requests?

Headphone answered 15/9, 2016 at 23:53 Comment(0)
B
3

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

Blackout answered 23/9, 2016 at 10:36 Comment(1)
Is there anyway that i can use this sequential async call with LiveData retrofitMinelayer

© 2022 - 2024 — McMap. All rights reserved.