0

我在我的新 Andriod 项目中将改造与 rxJava2 结合使用。我对 rxJava 1 的经验有限。

我的问题是:有没有更好的方法来写这个?我可能是错的,但这对我未经训练的眼睛来说看起来并不是很有吸引力:

public Single<Response<List<ProviderVO>>> getProviders(){
    if(Connectivity.isConnected(mContext)){ // test internet connection
        return mRetrofitHelper.getProviderList()
                .map(response -> {
                    if(response.code() == 200){
                        return Response.success(response.body().getProviders()
                                  ,response.raw());
                    } else {
                        return Response.<List<ProviderVO>>error(response.code()
                                  ,response.errorBody());
                    }
                })
                .doOnSuccess(response -> {
                    if(response.code() == 200){
                        mPreferencesHelper.putProviderList(response.body());
                    }
                });
    } else { // use cached providers when not connected to the internet
       List<ProviderVO> list = mPreferencesHelper.getProviderList();
       if (list != null){
           return Single.create(e -> e.onSuccess(Response.success(list)));
       } else {
           return Single.create(e -> e.onSuccess(Response.<List<ProviderVO>>error(400
                    ,ResponseBody.create(MediaType.parse("text/plain"), ""))));
       }
    }
}
4

1 回答 1

1

至少,您应该将所有 if/else 逻辑放入适当的方法中,例如:

.map(response -> {
                if(response.code() == 200){
                    return Response.success(response.body().getProviders()
                              ,response.raw());
                } else {
                    return Response.<List<ProviderVO>>error(response.code()
                              ,response.errorBody());
                }})

你可以像这样重写:

.map(this::handleResponse)

哪里handleResponse是:

private ResponseState handleResponse(Response response) {
    if(response.code() == 200){
           return Response.success(response.body().getProviders()
                          ,response.raw());
    } else {
            return Response.error(response.code()
                          ,response.errorBody());
    }
}

ResponseState如果响应成功与否,这里有一些带有标志的类。

此外,您可以为这种情况编写一个附加方法:

import io.reactivex.functions.Function;

public static <T, R> Function<? super T, ? extends Observable<? extends R>> decision(
        Function<T, Boolean> predicate,
        Function<? super T, ? extends Observable<? extends R>> ifTrue,
        Function<? super T, ? extends Observable<? extends R>> ifFalse) {
    return (item) -> predicate.apply(item)
            ? ifTrue.apply(item)
            : ifFalse.apply(item);
}

private ResponseState handleResponse(Response response) {
    return decision(response -> response.code() == 200,
            response -> Response.success(response.body().getProviders(), response.raw()),
            response -> Response.error(response.code(),response.errorBody()));

}
于 2017-01-20T07:39:10.460 回答