Retrofit+Rxjava+MVP初探
这段时间对这个模式关注的比较多,趁着项目还不是特别紧,写篇博客大致描述下几本步骤,研究较浅。
1.用之前需要知道的
(1)Retrofit是基于okHttp网络请求框架,加入注解,使的网络请求更加简洁.
(2)Rxjava异步框架,将网络加载过程和分发数据分解
(3)MVP代码开发模式,将数据和视图解耦合
2.配置gradle
compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
注意:在加入依赖的时候注意rxjava2:rxandroid和adapter-rxjava2都要保证是一个版本要么都是rxjava要么都是rxjava2,否则会报下面的错。详细错误解析
3.使用基本步骤
(1)配置客户端
public class ApiRetrofitClient {
private Retrofit retrofit_home;
public ApiRetrofitClient() {
initSetting();
}
private void initSetting() {
//创建ok请求客户端
File httpCacheFile = new File(ZZApplication.appContext.getCacheDir(),"cache");
Cache cache = new Cache(httpCacheFile, 24 * 1024 * 1024);
OkHttpClient okHttpClient = new OkHttpClient.Builder().cache(cache).build();
//创建retrofit客户端
retrofit_home = new Retrofit.Builder()
.baseUrl(HttpApi.PHP_API)
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public <T> T creat(Class<T> t){
T detailApi = retrofit_home.create(t);
return detailApi;
}
}
PS:做了最简单的配置,addConverterFactory用来配置解析库,一半采用的是GsonConverterFactory,因为个人项目的借口数据的原因,我将结果解析为String字符串,当然这个convert是可以自定义的,可以将数据转化为你想要的。详情参考
(2)创建请求接口
public interface HomeApi {
/**
* 请求首页推荐数据
* @param stringMap 参数map类型
* @return
*/
@FormUrlEncoded
@POST("home/")
Observable<String> getRecommandData(@FieldMap Map<String,String> stringMap);
}
由于Demo中之涉及到post请求,我这只贴一个接口了。详细参考
PS:注意两个小细节(@post里面的参数不能为空/baseUrl里面的必须以”/”结尾)
(3)创建统一回调
public interface ResponseCallBack<T> {
void success(T data);
void onError(Throwable e);
void onloading();
}
PS:按照mvp模式,这个任务本应该是View的职责–回显数据,但是究其根也是为了将数据和视图进行分离,而这个回调,是一个变向的View,无伤大雅。
(4)封装Observer,规范返回结果
public class HttpSubscriber<T> implements Observer<T> {
private ResponseCallBack<T> responseCallBack;
public HttpSubscriber(ResponseCallBack<T> responseCallBack) {
this.responseCallBack = responseCallBack;
}
@Override
public void onError(Throwable e) {
responseCallBack.onError(e);
}
@Override
public void onComplete() {
}
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(T t) {
responseCallBack.success(t);
}
}
(5)创建BaseModle
public class BaseModle {
public final ApiRetrofitClient apiRetrofitClient;
public BaseModle() {
apiRetrofitClient = new ApiRetrofitClient();
}
}
初始化ApiRetrofitClient
(6)创建HomeModle开始加载网络数据
public class HomeModle extends BaseModle {
public void loadHomeData(HttpSubscriber<String> baseResponseHttpSubscriber, Map<String, String> stringMap){
HomeApi homeAPI = apiRetrofitClient.creat(HomeApi.class);
Observable<String> recommandData = homeAPI.getRecommandData(stringMap);
recommandData.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(baseResponseHttpSubscriber);
}
}
(7)创建HomePresenter将数据和视图进行绑定
public class HomePresenter {
private ResponseCallBack<String> responseCallBack;
private final HomeModle homeModle;
public HomePresenter(ResponseCallBack<String> responseCallBack) {
this.responseCallBack = responseCallBack;
homeModle = new HomeModle();
}
public void getHomeData(Map<java.lang.String, java.lang.String> stringMap){
responseCallBack.onloading();
homeModle.loadHomeData(new HttpSubscriber<String>(responseCallBack),stringMap);
}
}
(8)View层展示数据
@Override
public void initData() {
HomePresenter homePresenter = new HomePresenter(baseResponseResponseCallBack);
HashMap<java.lang.String, java.lang.String> stringHashMap = new HashMap<>();
stringHashMap.put("member_from", "1");
java.lang.String sign = Utils.getSign(stringHashMap);
stringHashMap.put("sign", sign);
homePresenter.getHomeData(stringHashMap);
}
ResponseCallBack<String> baseResponseResponseCallBack = new ResponseCallBack<String>() {
@Override
public void success(String data) {
java.lang.String s = data.toString();
//解析数据
JSONTokener jsonTokener = new JSONTokener(data);
JSONObject jsonObject = null;
try {
jsonObject = (JSONObject) jsonTokener.nextValue();
int status = jsonObject.getInt("Code");
if (status == 1) {
Gson gson = new Gson();
RecommandBean recommandBean = gson.fromJson(data, RecommandBean.class);
if (switchShowView(recommandBean)) {
//设置数据
setDataForRecycleView(recommandBean, mActivity);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onloading() {
}
};