gpt4 book ai didi

error-handling - 改造Rxjava错误处理程序

转载 作者:行者123 更新时间:2023-12-03 07:53:45 25 4
gpt4 key购买 nike

我有一个用于调用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()?

最佳答案

您应该抛出运行时异常,并在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

关于error-handling - 改造Rxjava错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39993674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com