MVP+Retrofit+RXAndroid使用详解

最近研究在MVP设计模式下Retrofit结合RXandroid 构建程序网络交互模块,以此记录!

有关MVP讲解以及Retrofit&Rxandroid概述此处忽略:

直接Demo:

目录结构如下:(经典的MVP结构)

MVP+Retrofit+RXAndroid使用详解_第1张图片

demo模块模拟注册和登录:

mode层结构:

 (这里细分了 bean &biz & serviceapi 三个包)

MVP+Retrofit+RXAndroid使用详解_第2张图片
bean就是一些实体类,主要来看下 biz 和 serviceapi

 biz:主要定义了一些业务接口以及实现类:

  // 定义业务接口
public interface IBusiness {

    /**
     * 注册
     * @param mUserVo:请求参数:封装为bean
     * @param mICallBackListener:回调接口
     */
    public void register(UserVo mUserVo, ICallBackListener mICallBackListener);

    /**
     * 登录
     * @param obj:请求参数,可根据实际需求定义
     * @param  mICallBackListener:回调接口
     */
    public void login(Object obj, ICallBackListener mICallBackListener);

    /**
     * 忘记密码
     * @param obj:请求参数,可根据实际需求定义
     * @param  mICallBackListener:回调接口
     */
    public void forgetPwd(Object obj, ICallBackListener mICallBackListener);

    /**
     * 意见反馈
     * @param obj:请求参数,可根据实际需求定义
     * @param  mICallBackListener:回调接口
     */
    public void feedBack(Object obj, ICallBackListener mICallBackListener);

    //  TODO MORE
}

 //实现业务接口(Retrofit 结合 RxAndroid)
public class Business implements IBusiness {

    private static final String TAG = Business.class.getSimpleName();

    @Override
    public void register(UserVo mUserVo, final ICallBackListener mICallBackListener) {

        IServiceAPI mIServiceAPI = HttpDao.getInstance().getIServiceAPI();
        mIServiceAPI.register(mUserVo)
                // Subscriber前面执行的代码都是在I/O线程中运行
                .subscribeOn(Schedulers.io())
                // 操作observeOn之后操作主线程中运行.
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(HttpDao.getInstance().createSubscriber(mICallBackListener));
    }

    @Override
    public void login(Object obj, ICallBackListener mICallBackListener) {
        IServiceAPI mIServiceAPI =  HttpDao.getInstance().getIServiceAPI();
        mIServiceAPI.login("login",(UserVo)obj)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(HttpDao.getInstance().createSubscriber(mICallBackListener));
    }

    @Override
    public void forgetPwd(Object obj, ICallBackListener mICallBackListener) {
        // TODO
    }

    @Override
    public void feedBack(Object obj, ICallBackListener mICallBackListener) {
        // TODO
    }
}

// 定义 回调接口
public interface ICallBackListener {

    public void onSuccess(CallBackVo mCallBackVo);
    public void onFaild(CallBackVo mCallBackVo);

}

// HttpDao 主要对Refrofit以及RXAndroid中复用功能进行提取及整合封装为公用类

public class HttpDao {

    private static final String TAG = HttpDao.class.getSimpleName();
    private static HttpDao mHttpDao = null;
    private HttpDao() { } ;

    public static HttpDao getInstance() {
        if (mHttpDao == null) {
            mHttpDao = new HttpDao();
        }
        return mHttpDao;
    }

    /**
     * 获取 IServiceAPI实列
     * @return IServiceAPI
     */
    public IServiceAPI getIServiceAPI() {
        // 使用自定义转换器
        Gson mGson = new GsonBuilder()
                .registerTypeAdapter(String.class, new DeserializerData())
                .create();
        Retrofit mRetrofit = new Retrofit.Builder()
                .baseUrl(Consts.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(mGson))
                 //build.gradle引入:compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return mRetrofit.create(IServiceAPI.class);
    }

    /**
     * 创建 Subscriber
     * @param mICallBackListener
     * @return Subscriber
     */
    public Subscriber createSubscriber(final ICallBackListener mICallBackListener) {
        Subscriber mSubscriber = new Subscriber() {
            @Override
            public void onCompleted() {
                Log.i(TAG, "[onCompleted]");
            }
            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "[onError]" + e.getMessage());
                CallBackVo mCallBackVo = new CallBackVo();
                mCallBackVo.setResCode("400");
                mCallBackVo.setResMsg("请求失败");
                mCallBackVo.setResObj(null);
                mICallBackListener.onFaild(mCallBackVo);
                return;
            }
            @Override
            public void onNext(String s) {
                Log.i(TAG, "[onNext]" + s);
                Gson gosn = new Gson();
                CallBackVo mCallBackVo = gosn.fromJson(s, CallBackVo.class);
                if (mCallBackVo.getResCode().equals(Consts.REQUEST_SUCCESS_CODE)) {
                    mICallBackListener.onSuccess(mCallBackVo);
                } else {
                    mICallBackListener.onFaild(mCallBackVo);
                }
            }
        };
        return mSubscriber;
    }
}

 serviceapi:主要对reftofit框架定义了http的网络交互java接口以及自定义转换器:


// IserviceApi 定义网络交互 JAVA接口
public interface IServiceAPI {

    // 注册
    @POST("regist")
    Observable register(@Body UserVo mUserVo);

    // 登录
    @POST("{mode}")
    Observable login(@Path("mode") String value, @Body UserVo userVo);

}


// DeserializerData 自定义转换器/Gson对象

 
  
public class DeserializerData implements JsonDeserializer {
    @Override
    public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return json.toString();
    }
}
Mode层至此已经结束,下面看看View层
 
  

View层结构:

MVP+Retrofit+RXAndroid使用详解_第3张图片
为了直观这里创建activity以及iactivityview两个包,activity存放就是具体的Activity类,而iactivityview存放activity对应的接口view。
这里就拿注册作为案列:
先看注册view接口:
 
  
public interface IRegisterActivityView {

    /**
     * 获取参数
     *
     * @return
     */
    public UserVo getParamenters();

    /**
     * 显示操作进度
     */
    public void showProgress();

    /**
     * 关闭进度
     */
    public void closeProgress();

    /**
     * 成功回调
     */
    public void excuteSuccessCallBack(CallBackVo mCallBackVo);

    /**
     * 失败回调
     */
    public void excuteFailedCallBack(CallBackVo mCallBackVo);


}

IRegisterActivityView 为activity提供了基本的方法来操作view。
接下来activity实现该view接口实现并且实现对应的方法即可:
RegisterActivity:
 
  
public class RegisterActivity extends BaseActivity implements IRegisterActivityView {

    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.name)
    EditText name;
    @Bind(R.id.pwd)
    EditText pwd;
    @Bind(R.id.repwd)
    EditText repwd;
    @Bind(R.id.registerBt)
    Button registerBt;
    private RegisterActivityPresenter mRegisterActivityPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initView();
        mRegisterActivityPresenter = new RegisterActivityPresenter(this);
    }

    @Override
    public void initView() {
        super.initView();
        registerBt.setOnClickListener(this);
    }

    @Override
    public UserVo getParamenters() {
        UserVo mUserVo = new UserVo();
        mUserVo.setRegisterName(name.getText().toString());
        mUserVo.setRegisterPwd(pwd.getText().toString());
        mUserVo.setrRegisterPwd(repwd.getText().toString());
        return mUserVo;
    }

    @Override
    public void showProgress() {
        MDialog.getInstance(this).showProgressDialog();
    }

    @Override
    public void closeProgress() {
        MDialog.getInstance(this).closeProgressDialog();
    }

    @Override
    public void excuteSuccessCallBack(CallBackVo mCallBackVo) {
        RegisterVo mRegisterVo = (RegisterVo) mCallBackVo.getResObj();
        String name = mRegisterVo.getName();
        MDialog.getInstance(this).showToast(mCallBackVo.getResMsg() + "[" + name + "]");
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public void excuteFailedCallBack(CallBackVo mCallBackVo) {
        MDialog.getInstance(this).showToast(mCallBackVo.getResMsg());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.registerBt:
                String nameStr = name.getText().toString();
                String pwdStr = pwd.getText().toString();
                String rePwdStr = repwd.getText().toString();
                if (CommUtils.strISNull(nameStr) || CommUtils.strISNull(pwdStr) || CommUtils.strISNull(rePwdStr)) {
                    MDialog.getInstance(this).showToast("请填写完整信息");
                    return;
                } else if (!pwdStr.equals(rePwdStr)) {
                    MDialog.getInstance(this).showToast("密码不一致");
                    return;
                }
                mRegisterActivityPresenter.userRegister();
                break;
            default:
                break;
        }
    }
}

至此View层结束下面看看Presenter层:
 
  

presenter 层结构:

presenter层主要是View层与Mode层通信的桥梁,MVP模式View与Mode不直接进行数据交互因此通过Presenter来操作。
presenter层 定义了 V 对应的 P(同样看看注册)
public class RegisterActivityPresenter implements IBasePresenter {

    private IRegisterActivityView mIRegisterActivityView;

    public RegisterActivityPresenter(IRegisterActivityView mIRegisterActivityView) {
        this.mIRegisterActivityView = mIRegisterActivityView;
    }

    public void userRegister() {
        mIRegisterActivityView.showProgress();
        mIBusiness.register(mIRegisterActivityView.getParamenters(), new ICallBackListener() {
            @Override
            public void onSuccess(final CallBackVo mCallBackVo) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Gson mGson = new Gson();
                        JsonElement mJsonElement = mGson.toJsonTree(mCallBackVo.getResObj());
                        Type mType = new TypeToken() {
                        }.getType();
                        RegisterVo mRegisterVo = mGson.fromJson(mJsonElement, mType);
                        mCallBackVo.setResObj(mRegisterVo);
                        mIRegisterActivityView.closeProgress();
                        mIRegisterActivityView.excuteSuccessCallBack(mCallBackVo);
                    }
                });
            }

            @Override
            public void onFaild(final CallBackVo mCallBackVo) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mIRegisterActivityView.closeProgress();
                        mIRegisterActivityView.excuteFailedCallBack(mCallBackVo);
                    }
                });
            }
        });
    }
}
此 RegisterActivityPresenter 提供了一个注册功能,使用时在对应Activity中实例化该对象后即可调用所需方法:
MVP+Retrofit+RXAndroid使用详解_第4张图片

至此 M V P 层结构已经构建结束。
文中涉及[Retrofit]和 [Rxandroid]以及[ButterKnifeZelezny ] 的 build.gradle 配置如下:
// Retrofit(需要gson + adapter-rxjava)
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
// rxAndroid
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'
//ButterKnifeZelezny
compile 'com.jakewharton:butterknife:7.0.1'

GitHub地址:
RxAndroid
Retrofit
android-butterknife-zelezny

MVP+Retrofit+RXAndroid使用详解_第5张图片



 
   









你可能感兴趣的:(android开发总结)