我有一个服务类,用于调用api requset
这是一个示例方法:
public Observable<List<Category>> test(Location location, int radius) {
Observable<CategoryListResponse> observable = api.test();
return observable
.doOnNext(new Action1<CategoryListResponse>() {
@Override
public void call(CategoryListResponse categoryListResponse) {
//handle error
}
})
.flatMap(new Func1<CategoryListResponse, Observable<Category>>() {
@Override
public Observable<Category> call(CategoryListResponse categoryListResponse) {
return Observable.from(categoryListResponse.getCategories());
}
})
.map(new Func1<Category, Category>() {
@Override
public Category call(Category category) {
//do something...
return category;
}
})
.toList();
}
subscribe()将在另一个类中调用。
observable.subscribe(new Action1<List<Category>>() {
@Override
public void call(List<Category> categories) {
//on success
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
//on error
}
});
我想在返回之前在doOnNext()中进行错误处理。但是如何触发onError()?
答案 0 :(得分:1)
如果发生
,您应抛出运行时异常并控制onError运算符中的异常Observable<CategoryListResponse> observable = api.test();
return observable
.doOnNext(list -> {
try{
request(list);
catch(Exception e){
throw new RuntimeException(e);
}
}).onError(t->//Here you control your errors otherwise it will be passed to OnError callback in your subscriber)
.flatMap(item -> Observable.from(item.getCategories()))
.map(category-> category)
.toList();
}
尝试使用lambda,使代码更清晰,更易读 您可以在此处查看一些RxJava示例https://github.com/politrons/reactive