最近研究在MVP设计模式下Retrofit结合RXandroid 构建程序网络交互模块,以此记录!
有关MVP讲解以及Retrofit&Rxandroid概述此处忽略:
直接Demo:
(这里细分了 bean &biz & serviceapi 三个包)
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
}
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);
}
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;
}
}
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层
为了直观这里创建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);
}
接下来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;
}
}
}
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中实例化该对象后即可调用所需方法:
// 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'