改造 Rxjava 错误处理程序

Retrofit Rxjava error handler

我有一个服务class用来调用api请求

这是一个示例方法:

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() 将在另一个 class 中被调用。

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

尝试使用lambdas,让你的代码更清晰易读 您可以在此处查看一些 RxJava 示例 https://github.com/politrons/reactive