wobiancao / sugar

🍯 简单便捷 快速开发Android项目,集合流行框架封装mvp + rxjava2 + retrofit2 + rxlifecycle3 + arouter...
32 stars 7 forks source link

返回null怎么办 #8

Open as0026 opened 4 years ago

as0026 commented 4 years ago

接口返回的内容字段,返回null,这个应该很正常吧。现在rxjava的just发送null就报空指针,怎么统一处理这个?

wobiancao commented 4 years ago

新建xxRepository 继承 SugarRepository -> ObservableTransformer来处理 例子:

public class GankRepository extends SugarRepository implements RepositoryContract.GankModel {

    public GankRepository(BaseIView IView) {
        super(IView);
    }

    @Override
    public Gank getService() {
        return AppHttpClient.getInstance().initService(Gank.class);
    }

    @Override
    public <T> ObservableTransformer<GirlsResult<T>, T> gankTransformer() {

        return upstream -> upstream
                .flatMap((Function<GirlsResult<T>, ObservableSource<T>>) tGirlsResult -> {
### // 这里
                    if (tGirlsResult == null) {
                        return Observable.error(new HttpException("返回值为null"));
                    }
                    if (!tGirlsResult.error) {
                        return Observable.just(tGirlsResult.results);
                    } else {
                        return Observable.error(new HttpException("接口异常"));
                    }
                })

                ;

    }

    @Override
    public Observable<List<GirlsData>> getFuliDataRepository(String size, String index) {
        return addObservable(getService()
                .getFuliData(size, index)
                .compose(gankTransformer()), LOADING_TYPE_PAGE);
    }

}
as0026 commented 4 years ago

首先谢谢百忙中回复。然后我贴下我的代码把,我把ObservableTransformer进行了统一。 一、我的接口统一返回格式 { code:100, msg:"返回描述", data:null } data为T范型。

二、这个是某个模块功能的Repository: public class MainRepository extends BaseSugarRepository implements RepositoryContract.MainModel { public MainRepository(BaseIView IView) { super(IView); } @Override public Observable<List> getAdvertiging() { return addObservable(getService() .advertiging() .compose(commonTransformer()), LOADING_TYPE_NULL); } } 三、BaseSugarRepository.java代码,我把所有的接口都放到了HttpApi.java接口。 public class BaseSugarRepository extends SugarRepository { public BaseSugarRepository(BaseIView IView) { super(IView); } protected HttpApi getService() { return AppHttpClient.getInstance().initService(HttpApi.class); } protected ObservableTransformer<Response, T> commonTransformer() { return upstream -> upstream .flatMap((Function<Response, ObservableSource>) result -> { return flatData(result); }); } protected Observable flatData(Response result){ if (result == null) { return Observable.error(new HttpException(Response.EmptyCode,"返回值为空!")); }else if (result.getCode() == Response.SuccessCode) { return Observable.just(result.getData()); ##这里getData()可能返回null。 } else { return Observable.error(new HttpException(result.getCode(),result.getMsg())); } } }