回调地狱:排序RESTful Volley请求? RxAndroid? [英] Callback Hell: Sequencing RESTful Volley requests? RxAndroid?

查看:89
本文介绍了回调地狱:排序RESTful Volley请求? RxAndroid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看一个Android Java示例,该示例演示如何对异步(=非阻塞)RESTful Volley请求链进行排序.

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

这是RxAndroid的用途吗?

Is this what RxAndroid is used for?

  • 如果是这样,我想使用RxAndroid查看示例.
  • 如果没有,我仍然想看看跳入CALLBACK HELL的一个好例子!

我试图这样做,但是最终出现在CBHell中: 需要按顺序发送多个Volley请求

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

我希望将我的第一个请求的结果用于第二个请求.然后,我要在第三个请求中使用的第二个请求的结果.拜托,我该如何链接此类Volley请求?

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?

推荐答案

您可以使用flatMap方法,使用Rx链接多个请求.

You could use Rx to chain multiple requests by using the flatMap method.

flatMap要求您返回选择类型的另一个Observable,从而允许您与另一种类型进行异步操作.

flatMap requires you to return another Observable of the type of your chosing thus allowing you do something async with another type.

以下所有示例均使用新的rx v2制作.但是所有方法和机制也适用于v1

All of the examples below are made with the new rx v2. But all methods and mechanics also apply to v1

示例:

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
    }
});

这是MyVolleyApi哑类:

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

这篇关于回调地狱:排序RESTful Volley请求? RxAndroid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆