我在新的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"), ""))));
}
}
}
答案 0 :(得分: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()));
}