您可以使用Rx通过使用flatMap
方法链接多个请求。
flatMap
要求您返回另一个Observable
您的选择类型,因此您可以使用另一种类型进行异步操作。
以下所有示例均使用新的rx v2进行制作。但所有的方法和机制也适用于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());
}
}
这可以应用到任何东西,它不是在所有
volely具体
反正有,我可以使用这个连续的异步调用LiveData改造 –