Callback Hell: Sequencing RESTful Volley requests?

2019-04-14 01:57发布

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?

1条回答
看我几分像从前
2楼-- · 2019-04-14 02:33

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

查看更多
登录 后发表回答