一、引入
9102年了,终于准备用mvp来重构一下了
之前写过Mvc模式下的Retrofit统一异常处理,这次用MVP重构过程中发现诸多不足之处,便重新进行修缮,使其在我看来更加优雅emmmmmm,文中不足之处,还望诸位同仁多多指点。
推荐阅读:终于有人把 【移动开发】 从基础到实战的全套视频弄全了
二、基本流程描述
BaseView
BaseView接口定义了可能用到的方法,特别是addSubscribe,用来管理RxJava生命周期。
1public interface BaseView {
2
3 /**
4 * 显示吐司
5 *
6 * @param msg 提示消息
7 */
8 void showMsg(String msg);
9
10 /**
11 * 显示加载动画
12 */
13 void showProgress();
14
15 /**
16 * 显示提示
17 */
18 void showTip(@QMUITipDialog.Builder.IconType int iconType, CharSequence tipWord);
19
20 /**
21 * 关闭加载动画
22 */
23 void hideProgress();
24
25 /**
26 * 关闭提示
27 */
28 void hideTip();
29
30 /**
31 * 跳转页面
32 */
33 void startActivitySample(Class<?> cls);
34
35 /**
36 * Rx事件管理
37 *
38 * @param subscription
39 */
40 void addSubscribe(Disposable subscription);
41
42}
BasePresenter
BasePresenter方法中只定义了绑定View与解绑View的接口
1public interface BasePresenter<T extends BaseView> {
2
3 void attachView(T view);
4
5 void detachView();
6}
BaseActivity/Fragment
这个类是封装了一些常用方法,并且实现了BaseView的全部接口。 并且预留了两个用于mvp模式的空方法
1@Override
2protected void onCreate(@Nullable Bundle savedInstanceState) {
3 super.onCreate(savedInstanceState);
4 initContentView(R.layout.activity_base);
5 setContentView(getLayout());
6 mTopBar = (QMUITopBar) findViewById(R.id.base_topbar);
7 ButterKnife.bind(this);
8 mContext = this;
9 mSwipeBackLayout = getSwipeBackLayout();
10 if (isStartSwipeBack()) {
11 mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
12 } else {
13 mSwipeBackLayout.setEnableGesture(false);
14 }
15 AppManager.addActivity(this);
16 // 在此处调用绑定Presenter方法
17 initPresenter();
18 initEventAndData();
19}
20
21@Override
22protected void onDestroy() {
23 unSubscribe();
24 removePresenter();
25 AppManager.removeActivity(this);
26 super.onDestroy();
27}
28
29protected void initPresenter() {
30
31}
32
33protected void removePresenter() {
34
35}
BaseMvpActivity/Fragment
实现了BaseActivity/Fragment中的预留方法
1public abstract class BaseMvpActivity<T extends BasePresenter> extends BaseActivity {
2
3 protected T mPresenter;
4
5 @Override
6 protected void initPresenter() {
7 mPresenter = createPresenter();
8 if (mPresenter != null) {
9 mPresenter.attachView(this);
10