本篇是 Mvp + okhttp2 + retrofit2 + rxjava2 的简单封装
定义一个 BaseView,定义几个公共的方法
public interface BaseView {
//网络请求开始时回调
void netStart();
//请求报错时回调
void netError(String msg);
//结束时回调¬
void netEnd();
}
定义一个 BaseModel,什么都没有操作,只是做一个简单的声明
public interface BaseModel {
}
定义一个 BasePresenter,做设置 view 和 model ,使用 rxjava 管理
public abstract class BasePresenter<V extends BaseView, M extends BaseModel> {
protected V mView;
protected M mModel;
//该类是用户管理请求的
public RxManager mRxManager = new RxManager();
public void setVM(V mView, M mModel) {
this.mModel = mModel;
this.mView = mView;
}
protected void register(Subscription s) {
mRxManager.add(s);
}
void unregister() {
mRxManager.clear();
}
//设置 rxjava 线程切换,减少代码
protected <T> Observable<T> observe(Observable<T> observable) {
return observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
}
public class RxManager {
//使用 rxjava 中的 CompositeSubscription 来管理
CompositeSubscription mSubscription;
public RxManager() {
mSubscription = new CompositeSubscription();
}
public void add(Subscription s) {
mSubscription.add(s);
}
public void clear() {
mSubscription.clear();
}
}
定义一个 BaseMvpActivity,实现关联
//通过定义泛型 获取不同的 P,M
public abstract class BaseMvpActivity<P extends BasePresenter, M extends BaseModel> extends BaseActivity implements BaseView {
public P mPresenter;
public M mModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
mPresenter = getPresenter();
mModel = getModel();
mPresenter.setVM(this, mModel);
super.onCreate(savedInstanceState);
}
@Override
protected void onDestroy() {
//页面销毁是解注册
super.onDestroy();
if (mPresenter != null) {
mPresenter.unregister();
}
}
protected abstract P getPresenter();
protected abstract M getModel();
}
定义完这几个基本差不多,按照谷歌推出的 Mvp 还需要定义一个 Contract 来集中管理,下面假设实现一个登录功能,定义一个 LoginContract
public interface LoginContract {
interface View extends BaseView {
//接口调用成功返回数据
void getLogin(LoginBean loginBean);
}
interface Model extends BaseModel {
//定义 model 获取数据
Observable<LoginBean> login(String phone, String psw);
}
abstract class Presenter extends BasePresenter<View, Model> {
//定义 Presenter
public abstract void login(String phone, String psw);
}
}
书写 LoginModel
public class LoginModel implements LoginContract.Model {
@Override
public Observable<LoginBean> login(String phone, String psw) {
//使用okhttp2 + retrofit2 获取数据,后面在说
return Api.getInstance().getApiSevice().login();
}
}
书写 LoginPresenter
public class LoginPresenter extends LoginContract.Presenter {
@Override
public void login(String phone, String psw) {
//注册,使用 rxjava 进行线程调度
register(observe(mModel.login(phone, psw))
.subscribe(new Subscriber<LoginBean>() {
@Override
public void onCompleted() {
mView.netStart();
}
@Override
public void onError(Throwable e) {
mView.netError(e.getMessage());
}
@Override
public void onNext(LoginBean loginBean) {
mView.getLogin(loginBean);
mView.netEnd();
}
}));
}
}
书写 LoginActivity
//注意实现 LoginContract.View 不然会报错,而且没有报错日志
public class LoginActivity extends BaseMvpActivity<LoginPresenter, LoginModel> implements LoginContract.View {
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected LoginPresenter getPresenter() {
//生成具体的 Presenter
return new LoginPresenter();
}
@Override
protected LoginModel getModel() {
//生成具体的Model
return new LoginModel();
}
@Override
protected void initDate() {
}
@Override
protected void initView() {
//LoginActivity 里面就放了一个按钮点击
findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.login("", "");
}
});
}
@Override
public void netStart() {
}
@Override
public void netError(String msg) {
}
@Override
public void netEnd() {
}
@Override
public void getLogin(LoginBean loginBean) {
//接口调用完毕后会回调这里
}
}
Mvp 的封装大体就这样子,接下来来看 网络请求。
定义 Api 类
public class Api {
//连接超时时间
private static final int DEFAULT_TIME_OUT = 60;
//读写超时
private static final int DEFAULT_READ_TIME_OUT = 60;
private final Retrofit mRetrofit;
private static class SingletonHolder {
private static final Api INSTANCE = new Api();
}
public static Api getInstance() {
return SingletonHolder.INSTANCE;
}
//构造函数中创建 OkHttpClient 和 Retrofit 对象
private Api() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);//连接超时时间
builder.writeTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//写操作 超时时间
builder.readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//读操作 超时时间
//日志拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);
mRetrofit = new Retrofit.Builder()
.client(builder.build())
.baseUrl(ApiConfigure.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
//创建 ApiServices
public ApiServices getApiSevice() {
return create(ApiServices.class);
}
//创建 Service
private <T> T create(Class<T> clazz) {
return mRetrofit.create(clazz);
}
}
定义 ApiServices 存放请求接口
public interface ApiServices {
@GET("json")
Observable<LoginBean> login();
}
最后使用方式
Api.getInstance().getApiSevice().login();
最后附上 demo地址