感谢玩Android提供的API
Retrofit + Rx + OkHttp MVP
MVP 模式下的 Retrofit + Rx + OkHttp 网络上有许多,这篇文章是自己对 MVP 的一些理解和感悟,希望能够帮助到读者。
准备工作
- 依赖
- 网络
- 基类
- MVP 使用
依赖
//Okhttp
implementation 'com.squareup.okhttp3:logging-interceptor:3.+'
//rxjava
implementation 'io.reactivex.rxjava2:rxjava:2.+'
implementation 'io.reactivex.rxjava2:rxandroid:2.+'
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.+'
implementation 'com.google.code.gson:gson:2.+'
//Gson 库
implementation 'com.squareup.retrofit2:converter-gson:2.+'
//转换器,请求结果转换成Model
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.+'
网络封装 RetrofitManager
public class RetrofitManager {
private static final int DEFAULT_TIME_OUT = 30;//超时时间
private static final int DEFAULT_READ_TIME_OUT = 60;//读写超时
long SIZE_OF_CACHE = 10 * 1024 * 1024; // 10 MB
String cacheFile = App.getApplication().getCacheDir() + "/mvp/http";
Cache cache = new Cache(new File(cacheFile), SIZE_OF_CACHE);
static volatile RetrofitManager retrofitManager = null;
private Retrofit mRetrofit;
private RetrofitManager() {
//初始化okhttp
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// log用拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// 开发模式记录整个body,否则只记录基本信息如返回200,http协议版本等
if (BuildConfig.DEBUG) {
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
} else {
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
}
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().build();
return chain.proceed(request);
}
});
builder.cache(cache) //设置缓存目录
.addInterceptor(loggingInterceptor)
.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)//设置超时
.readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
.retryOnConnectionFailure(true);//错误重连
OkHttpClient client = builder.build();
mRetrofit = new Retrofit.Builder()
.baseUrl(API.BASE_URL)
//设置 Json 转换器
.addConverterFactory(GsonConverterFactory.create())
//添加call转换器将call转换成Observe(观察者)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
}
/**
* DCL双重检索
* 单例模式
* @return
*/
public static RetrofitManager getRetofitManager(){
if(retrofitManager==null){
synchronized (RetrofitManager.class) {
if (retrofitManager == null) {
retrofitManager = new RetrofitManager();
}
}
}
return retrofitManager;
}
/**
* 获取对应的Service
*
* @param service Service 的 class
* @param
* @return
*/
public T create(Class service) {
return mRetrofit.create(service);
}
}
基类
BasePresenter
public interface BasePresenter {
/**
* 绑定
*/
void attachView(T t);
/**
* 解除绑定
*/
void detachView();
}
BaseLoader
public class BaseLoader implements Function, T> {
@Override
public T apply(Response tResponse) throws Exception {
//todo 可以自定义处理回掉参数
return tResponse.getData();
}
}
ObjectLoader
protected Observable observe(Observable observable) {
//被观察者线程 io线程,读写,网络操作
return observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
//观察者线程 Androidui线程
.observeOn(AndroidSchedulers.mainThread());
}
BaseView
public interface BaseView {
//todo 例如获取token等
}
MVP 使用 ( 面向接口 )
- 请求地址
public interface API {
String BASE_URL = "https://www.wanandroid.com/";
String TEST = "friend/json";
}
- 将页面要用到的接口统一抽取
MainContract
public class MainContract {
/**
* P 层
*/
public interface Presenter extends BasePresenter {
void showMessage();
}
/**
* V 层
*/
public interface View extends BaseView {
void showSuccess(String s);
void showFail(String s);
}
/**
* M 层
*/
public interface Service {
@GET(API.TEST)
Observable>> getMessage();
}
}
- M
TestEntity
public class TestEntity implements Serializable {
private String icon;
private String id;
private String link;
private String name;
private String order;
private String visible;
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public String getVisible() {
return visible;
}
public void setVisible(String visible) {
this.visible = visible;
}
}
- P
MainLoader
public class MainLoader extends ObjectLoader {
private MainContract.Service mainService;
public MainLoader(){
mainService = RetrofitManager.getRetofitManager().create(MainContract.Service.class);
}
public Observable> getMessage(){
return observe(mainService.getMessage()).map(new BaseLoader>());
}
}
MainPresenterImpl
public class MainPresenterImpl implements MainContract.Presenter {
private MainContract.View view;
private MainLoader mainLoader;
private Context context;
public MainPresenterImpl(Context context) {
this.context = context;
this.mainLoader = new MainLoader();
}
@Override
public void attachView(MainContract.View view) {
this.view = view;
}
@Override
public void detachView() {
this.view = null;
}
@Override
public void showMessage() {
Observable> observable = null;
try {
observable = mainLoader.getMessage();
} catch (Exception e) {
view.showFail(context.getResources().getString(R.string.request_fail));
return;
}
observable.subscribe(new Consumer>() {
@Override
public void accept(List o) {
//这里没有处理,只是返回测试结果,具体实现看功能
view.showSuccess(new Gson().toJson(o));
}
}, new Consumer() {
@Override
public void accept(Throwable throwable) throws Exception {
//异常封装
view.showFail(throwable.getMessage());
}
});
}
}
- V
MainActivity
public class MainActivity extends AppCompatActivity implements MainContract.View {
private MainPresenterImpl mainPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mainPresenter = new MainPresenterImpl(this);
mainPresenter.attachView(this);
mainPresenter.showMessage();
}
@Override
protected void onDestroy() {
super.onDestroy();
mainPresenter.detachView();
}
@Override
public void showSuccess(String s) {
ToastUtil.getToastUtil(this).showToast("success>>>>>"+s);
}
@Override
public void showFail(String s) {
ToastUtil.getToastUtil(this).showToast("fail>>>>>"+s);
}
}
感谢玩Android提供的API