前面说了RxJava 与Retrofit的基本用法,但是没用做优化的处理.本篇先做一个优化处理,然后再结合前面的MVP 设计模式,把这些知识贯穿到一个Demo 之中,方便大家理解.
BaseResponse与BaseObserver的封装
BaseResponse是个人自定义命名的一个类,主要用来对返回数据进行抽象。
BaseObserver是对返回数据的基础数据部分进行统一处理。
BaseResponse就是对基础数据进行封装处理。
修改API接口返回数据类型,对基础数据进行封装处理
我的数据类型是返回的是数组,那么我们定义的则是
public class BaseListResponse<T> implements Serializable {
private String msg;
private int status;
private List<T> result;
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
有人问了 如果返回的是对象 那你怎么办?? 不要担心 马上定义
public class BaseResponse<T> implements Serializable {
private String msg;
private int status;
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
private T result;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
对返回数据的处理
.subscribe(new Observer<BaseListResponse<GoodsBean>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(BaseListResponse<GoodsBean> goodsList) {
etUserName.setText(goodsList.getResult().get(1).getP_name());
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
对基础数据统一封装处理 这里以返回的类型是数组为例
public abstract class BaseObserverList<T> implements Observer<BaseListResponse<T>> {
private static final String TAG = "BaseObserverList";
@Override
public void onSubscribe(Disposable d) {
Log.e(TAG, "onSubscribe: ");
}
@Override
public void onNext(BaseListResponse<T> response) {
//在这边对 基础数据 进行统一处理 举个例子:
if (response.getStatus() == 0) {
onSuccess(response.getResult());
} else {
onFailure(null, response.getMsg());
}
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "Throwable: " + e.getMessage());
}
@Override
public void onComplete() {
Log.e(TAG, "onComplete: ");
}
public abstract void onSuccess(List<T> demo);
public abstract void onFailure(Throwable e, String errorMsg);
}
请求网络数据
Api api = retrofit.create(Api.class);
api.getCall("0", "1")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BaseObserverList<GoodsBean>() {
@Override
public void onSuccess(List<GoodsBean> list) {
//请求成功
etUserName.setText(list.get(0).getP_name());
}
@Override
public void onFailure(Throwable e, String errorMsg) {
}
});
接下来我要说的 就是MVP 设计模式 下 请求网络获取商品列表并展示的过程了
这个是效果图 就是请求网络并获取商品列表的功能
根据之前 MVP 设计模式,外加RxJava+Retrofit 网络请求 整合在一起
mvp 接口管理类
public interface HomeGoodsContract {
interface Model {
void GoodsList(String cid, String page, OnGoodsListener goodsListener);
}
interface View {
void showFail();
void showLoading();
void hideLoading();
//展示商品列表
void showGoodsList(List<GoodsBean> result);
}
interface Presenter {
void getGoodsList();
}
}
Model层
public class HomeGoodsModel implements HomeGoodsContract.Model {
private HomeGoodsActivity context;
public HomeGoodsModel(HomeGoodsActivity context) {
this.context = context;
}
@Override
public void GoodsList(String cid, String page,final OnGoodsListener goodsListener) {
RequestUtils.PutCall(context, cid, page, new BaseObserverList<GoodsBean>() {
@Override
public void onSuccess(List<GoodsBean> demo) {
goodsListener.getGoodsSuccess(demo);
}
@Override
public void onFailure(Throwable e, String errorMsg) {
goodsListener.getGoodsFailed();
}
});
}
}
这里面有两个类 OnGoodsListener 接口类 RequestUtils 提交参数的管理类
RequestUtils 提交参数的管理类
//提交参数的管理类
public class RequestUtils {
public static void PutCall(HomeGoodsActivity context, String cid, String page, BaseObserverList<GoodsBean> consumer){
RetrofitUtils.getApiUrl()
.getCall(cid,page).compose(RxHelper.observableIO2Main(context))
.subscribe(consumer);
}
}
OnGoodsListener 接口回调
//接口回调类
public interface OnGoodsListener {
//获取商品列表成功的回调
void getGoodsSuccess(List<GoodsBean> result);
//获取失败的回调
void getGoodsFailed();
}
之后的一些工具类我放在本文的最后 并附加源码
Presenter层中的操作
public class HomeGoodsPresenter implements HomeGoodsContract.Presenter {
private HomeGoodsContract.View homeGoodsView;
private HomeGoodsModel homeGoodModel;
//Presenter必须要能拿到View和Model的实现类
public HomeGoodsPresenter(HomeGoodsActivity context, HomeGoodsContract.View view) {
this.homeGoodsView = view;
this.homeGoodModel = new HomeGoodsModel(context);
}
@Override
public void getGoodsList() {
homeGoodsView.showLoading();
//填写请求参数
homeGoodModel.GoodsList("0", "1", new OnGoodsListener() {
@Override
public void getGoodsSuccess(List<GoodsBean> result) {
homeGoodsView.showGoodsList(result);
homeGoodsView.hideLoading();
}
@Override
public void getGoodsFailed() {
homeGoodsView.showFail();
homeGoodsView.hideLoading();
}
});
}
}
最后则是View 的操作了
public class HomeGoodsActivity extends RxActivity implements HomeGoodsContract.View {
private HomeGoodsPresenter presenter;
private LoadingDialog loadingDialog;
private RecyclerView rcList;
private ShopMallGoodsAdapter adapterX;
private List<GoodsBean> shopGoodsList;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
presenter = new HomeGoodsPresenter(HomeGoodsActivity.this, this);
initView();
}
private void initView() {
loadingDialog = new LoadingDialog(HomeGoodsActivity.this, "加载中...");
shopGoodsList = new ArrayList<>();
rcList = findViewById(R.id.rc_list);
SpaceItemDecoration spaceItemDecoration = new SpaceItemDecoration(AutoSizeUtils.dp2px(this, 1.5f));
rcList.addItemDecoration(spaceItemDecoration);
adapterX = new ShopMallGoodsAdapter(R.layout.item_peijian_shop, shopGoodsList);
View view = LayoutInflater.from(this).inflate(R.layout.list_no_data_new, rcList, false);
ImageView noGoods = view.findViewById(R.id.no_goods);
noGoods.setVisibility(View.VISIBLE);
TextView tv_msg = view.findViewById(R.id.tv_msg);
tv_msg.setText("没有相关商品");
adapterX.setEmptyView(view);
adapterX.isUseEmpty(false);
rcList.setAdapter(adapterX);
//获取商品
presenter.getGoodsList();
}
@Override
public void showFail() {
Toast.makeText(this, "获取商品列表失败", Toast.LENGTH_SHORT).show();
}
@Override
public void showLoading() {
loadingDialog.show();
}
@Override
public void hideLoading() {
loadingDialog.dismiss();
}
@Override
public void showGoodsList(List<GoodsBean> result) {
if (result.isEmpty() || result == null || result.size() == 0) {
adapterX.isUseEmpty(true);
}
shopGoodsList.addAll(result);
adapterX.notifyDataSetChanged();
}
}
剩下的则是我说的有关一些工具类了
RxHelper 调度类
public class RxHelper {
public static <T> ObservableTransformer<T, T> observableIO2Main(final Context context) {
return new ObservableTransformer<T, T>() {
@Override
public ObservableSource<T> apply(Observable<T> upstream) {
Observable<T> observable = upstream.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
return composeContext(context, observable);
}
};
}
public static <T> ObservableTransformer<T, T> observableIO2Main(final RxFragment fragment) {
return upstream -> upstream.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).compose(fragment.<T>bindToLifecycle());
}
public static <T> FlowableTransformer<T, T> flowableIO2Main() {
return new FlowableTransformer<T, T>() {
@Override
public Publisher<T> apply(Flowable<T> upstream) {
return upstream
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
private static <T> ObservableSource<T> composeContext(Context context, Observable<T> observable) {
if(context instanceof RxActivity) {
return observable.compose(((RxActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
} else if(context instanceof RxFragmentActivity){
return observable.compose(((RxFragmentActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
}else if(context instanceof RxAppCompatActivity){
return observable.compose(((RxAppCompatActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
}else {
return observable;
}
}
}
异常处理类
public class RxExceptionUtil {
public static String exceptionHandler(Throwable e){
String errorMsg = "未知错误";
if (e instanceof UnknownHostException) {
errorMsg = "网络不可用";
} else if (e instanceof SocketTimeoutException) {
errorMsg = "请求网络超时";
} else if (e instanceof HttpException) {
HttpException httpException = (HttpException) e;
errorMsg = convertStatusCode(httpException);
} else if (e instanceof ParseException || e instanceof JSONException
|| e instanceof JSONException) {
errorMsg = "数据解析错误";
}
return errorMsg;
}
private static String convertStatusCode(HttpException httpException) {
String msg;
if (httpException.code() >= 500 && httpException.code() < 600) {
msg = "服务器处理请求出错";
} else if (httpException.code() >= 400 && httpException.code() < 500) {
msg = "服务器无法处理请求";
} else if (httpException.code() >= 300 && httpException.code() < 400) {
msg = "请求被重定向到其他页面";
} else {
msg = httpException.message();
}
return msg;
}
}
RetrofitUtils 工具类
public class RetrofitUtils {
private static final String TAG = "RetrofitUtils";
private static Api mApiUrl;
/** * 单例模式 */
public static Api getApiUrl() {
if (mApiUrl == null) {
synchronized (RetrofitUtils.class) {
if (mApiUrl == null) {
mApiUrl = new RetrofitUtils().getRetrofit();
}
}
}
return mApiUrl;
}
private RetrofitUtils(){
}
public Api getRetrofit() {
// 初始化Retrofit
Api apiUrl = initRetrofit(initOkHttp()) .create(Api.class);
return apiUrl;
}
/** * 初始化Retrofit */
@NonNull
private Retrofit initRetrofit(OkHttpClient client) {
return new Retrofit.Builder()
.client(client)
.baseUrl(Constant.IP)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
/** * 初始化okhttp */
@NonNull
private OkHttpClient initOkHttp() {
return new OkHttpClient().newBuilder()
.readTimeout(Constant.DEFAULT_TIME, TimeUnit.SECONDS)//设置读取超时时间
.connectTimeout(Constant.DEFAULT_TIME, TimeUnit.SECONDS)//设置请求超时时间
.writeTimeout(Constant.DEFAULT_TIME,TimeUnit.SECONDS)//设置写入超时时间
.addInterceptor(new LogInterceptor())//添加打印拦截器
.retryOnConnectionFailure(true)//设置出现错误进行重新连接。
.build();
}
}
关于源码 大家只需要看Goods类中的就可以了
源码下载地址:
https://download.csdn.net/download/MacaoPark/12598137
希望可以帮到你
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/2820.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...