封装RxJava+Retrofit导入依赖
compile 'io.reactivex.rxjava2:rxjava:2.1.1' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' //工具类public interface ApiService { @GET("api/data/Android/10/1") Flowable<AndroidBean> getAndroid(@QueryMap Map<String, String> map); }
//model层public class RetrofitUtils { private static volatile RetrofitUtils instance; private final Retrofit retrofit; private RetrofitUtils() { retrofit = new Retrofit.Builder() .baseUrl("http://gank.io/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static RetrofitUtils getInstance() { if (instance == null) { synchronized (RetrofitUtils.class) { if (instance == null) { instance = new RetrofitUtils(); } } } return instance; } public Retrofit getRetrofit() { return retrofit; } }
public interface IModel {
void get(Map<String,String> map);
}
public class AndroidModel implements IModel{
private AndroidPresenter presenter;
public AndroidModel(AndroidPresenter presenter) {
this.presenter = presenter;
}
@Override
public void get(Map<String, String> map) {
Flowable<AndroidBean> android = RetrofitUtils.getInstance().getRetrofit().create(ApiService.class).getAndroid(map);
presenter.getData(android);
}
}
//view层
public interface IView {
void onSuccess(Object o);
void onFailed(Exception e);
}
//presenter层
public interface BasePresenter {
void get(Map<String,String> map);
}
public class AndroidPresenter implements BasePresenter {
private IView iv;
private DisposableSubscriber subscriber;
public AndroidPresenter(IView iv) {
this.iv = iv;
}
@Override
public void get(Map<String, String> map) {
AndroidModel model = new AndroidModel(this);
model.get(map);
}
public void getData(Flowable flowable) {
subscriber = (DisposableSubscriber) flowable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableSubscriber() {
@Override
public void onNext(Object o) {
iv.onSuccess(o);
Log.e("CDM", "onNext: o" + "数据请求成功");
}
@Override
public void onError(Throwable t) {
iv.onFailed((Exception) t);
Log.e("CDM", "onNext: o" + "数据请求失败");
}
@Override
public void onComplete() {
}
});
}
//防止内存泄漏
public void detachView() {
if (iv != null) {
iv = null;
}
if (subscriber != null) {
if (!subscriber.isDisposed()) {
subscriber.dispose();
}
}
}
}
//最后在mainActivity里实现ivew接口,调用p层