MVP+retrofit+rxjava

retrofit和rxjava最近比较火,但是他们确实让代码架构更加清楚了。

先介绍一下适用三者需要的配置:

1.需要一下配置

        compile'com.squareup.retrofit2:retrofit:2.1.0'

        compile'com.squareup.retrofit2:converter-gson:2.1.0'

        compile'com.squareup.okhttp3:logging-interceptor:3.4.1'

        compile'com.squareup.retrofit2:adapter-rxjava:2.1.0'

        compile'io.reactivex:rxandroid:1.2.1'

配置完成了之后我们需要构建基本的架构:

初始化retrofit+自定义请求头(方便在头中自定义一下信息):

private staticRetrofit initRetrofit() {

          OkHttpClient client=genericClient(L.open);

          return newRetrofit.Builder().baseUrl(基础的url).client(client)

                    .addConverterFactory(GsonConverterFactory.create())

                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//rx回调

                    .build();

}

public staticOkHttpClient genericClient(booleandebug) {

           HttpLoggingInterceptor      logging=new   HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger(){

            @Override

             public void  log(String message) {

                       L.e(message);

              }

});

logging.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client=null;

if(debug){

client=newOkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)

.addInterceptor(newBaseInterceptor(addHeader())).addInterceptor(logging)

.writeTimeout(10,TimeUnit.SECONDS).build();

}else{

client=newOkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)

.addInterceptor(newBaseInterceptor(addHeader()))

.writeTimeout(10,TimeUnit.SECONDS).build();

}

returnclient;

}

基础拦截器的代码大致如下:

public classBaseInterceptorimplementsInterceptor{

privateMapheaders;

publicBaseInterceptor(Map headers){

this.headers=headers;

}

@Override

publicResponse intercept(Chain chain)throwsIOException {

Request.Builder builder=chain.request().newBuilder();

if(headers!=null&&headers.size()>0){

Set keys=headers.keySet();

for(String headerKey:keys) {

builder.addHeader(headerKey,headers.get(headerKey)).build();

}

}

Response response=chain.proceed(builder.build());

for(inti =0; i < response.headers().size(); i++) {

if(response.headers().value(i).contains("tmbj-token=")) {

intindex = response.headers().value(i).indexOf(";");

SPUtils.setValue(SPfileds.TMBJ_TOKEN, response.headers().value(i).substring(0, index).replace("tmbj-token=",""));

}

}

returnresponse;

}

}

定义接口调用的接口api(因为我们公司先前是表单提交):

@FormUrlEncoded

@POST("user/login")

Observable> login(@Field("userInfo.mobile") String mobile,@Field("userInfo.passWord") String pwd);

服务器返回数据的封装:

public classRxResultHelper {

public static Observable.Transformer,T> handleResult() {

return newObservable.Transformer,T>() {

@Override

publicObservable call(Observable> tObservable) {

returntObservable.flatMap(

newFunc1, Observable>() {

@Override

publicObservable call(BaseResult result) {

if(result.code==0) {

returncreateData(result.data);

}else if(result.code==10001) {

多个用户登录

}else{

if(result!=null){

returnObservable.error(new ArromException(result.massage));

}

}

returnObservable.empty();

}

}

).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());

}

};

}

private static Observable createData(finalTdata) {

returnObservable.create(newObservable.OnSubscribe() {

@Override

public voidcall(Subscriber subscriber) {

try{

if(!subscriber.isUnsubscribed()){//如果订阅了

subscriber.onNext(data);

subscriber.onCompleted();

}

}catch(Exception e) {

subscriber.onError(e);

}

}

});

}

}

自定义订阅者:

public abstract classRxSubscriberextendsSubscriber {

@Override

public voidonCompleted() {

}

@Override

public voidonError(Throwable e) {

e.printStackTrace();

//网络不可用

if(!NetUtils.isConnected(Application.getInstance())){

rx_Error("网络不可用");

return;

}

//服务器返回的错误

if(einstanceofTMBJException){

rx_Error(e.getMessage());

}else{

rx_Error("请求失败,请稍后重试");

}

}

@Override

public voidonNext(Tt) {

rx_Next(t);

}

public abstract voidrx_Next(Tt);

public abstract voidrx_Error(String msg);

}

简单调用:

TMBJProtocol.enqueue(UserService.class).login(mobile,password)

.compose(RxResultHelper.handleResult())

.subscribe(newRxSubscriber() {

@Override

public voidrx_Next(LoginBean loginBean) {

view.hideLoading();

view.setNetDataSuccess(loginBean);

}

@Override

public voidrx_Error(String msg) {

view.hideLoading();

view.setNetDataFail(msg);

}

});

好像忘记介绍mvp了,我会将demo代码提交到github上https://github.com/xujie198705292135/ArromFramework.git

你可能感兴趣的:(MVP+retrofit+rxjava)