Retrofit+Rxjava+MVP网络请求框架

3 篇文章 0 订阅
3 篇文章 0 订阅

android MVC框架模式:
概念: MVC即Model(模型)-View(视图)-Controller(控制器)
用途:模块化设计,低耦合可扩展,提升效率
模型(数据层):本地数据库及操作,网络数据库操作
视图(界面层):图形界面,layout布局及各种控件
控制器(响应层):用户按键及触摸事件

一句话总结:用户在某个软件里购物,你点击那个购物图片,这就会触发控制器响应层,控制器就会从模型层获取数据(网络或本地数据库),最后将获得的数据显示到视图层给你看相关信息.

以上是MVC,只是理解,这里有套基于MVP的网络请求框架,是okhttp封装的,后来由于retrofit,rxJava的流行

释义:
retrofit:基于okhttp再次封装的网络请求框架
rxjava:异步工具库,handler+thread->asyctask->rxjava->rxandroid
mvp:相对于mvc的框架模式

步骤:
1:导包

    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.11'

2:回调接口

public interface PresenterCallback<M> {

    void getDataSuccess(M model);

    void getDataFail(String msg);
}

3:Model数据层

public class LoginBean {
    public ContentBean content;
    public Hints hints;

    public static class ContentBean {
        public String identity;
        public String nickname;
        public String avatar;
        public int enumers;
        public Object token;
        public String loginame;
        public String organ;
        public String openId;
        public String msgcode;
    }

    public static class Hints {
        public String status;
        public Hints.Tip tips;

        public static class Tip {
            public List<Hints.Tip.Detail> details;

            public static class Detail {
                public String code;
                public List<String> args;

            }
        }
    }
}

4:presenter层,逻辑控制层

public class Presenter<M> {
    public Retrofit mRetrofit;
    public PresenterCallback presenterCallback;
    public RetrofitUrl retrofitUrl;
    public CompositeDisposable mCompositeDisposable;

    public Presenter(PresenterCallback presenterCallback) {
        this.presenterCallback = presenterCallback;
        retrofitUrl = retrofit().create(RetrofitUrl.class);
    }

    //取消rxjava
    public void disposeRx() {
        this.presenterCallback = null;
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    //初始化retrofit
    public Retrofit retrofit() {
        if (mRetrofit == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(loggingInterceptor);
            }
            OkHttpClient okHttpClient = builder.build();
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(UrlContainer.HOST_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return mRetrofit;
    }

    //初始化rxJava
    public void addSubscription(Observable observable, DisposableObserver observer) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(observer);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer);
    }

    //获取登录信息
    public void getLoginData(Map hashMap) {
        addSubscription(retrofitUrl.loginData(hashMap), new ObserverCallback<M>() {
            @Override
            public void onSuccess(M model) {
                presenterCallback.getDataSuccess(model);
            }

            @Override
            public void onFailure(String msg) {
                presenterCallback.getDataFail(msg);
            }

            @Override
            public void onFinish() {
            }
        });
    }

    //URL接口
    public interface RetrofitUrl {
        //登录信息
        @FormUrlEncoded
        @POST("a/login.json")
        Observable<LoginBean> loginData(@FieldMap Map<String, String> params);
    }

    //observer类
    public abstract class ObserverCallback<M> extends DisposableObserver<M> {

        public abstract void onSuccess(M model);

        public abstract void onFailure(String msg);

        public abstract void onFinish();

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            if (e instanceof HttpException) {
                HttpException httpException = (HttpException) e;
                int code = httpException.code();
                String msg = httpException.getMessage();
                if (code == 504) {
                    msg = "网络不给力";
                }
                if (code == 502 || code == 404) {
                    msg = "服务器异常,请稍后再试";
                }
                onFailure(msg);
            } else {
                onFailure(e.getMessage());
            }
            onFinish();
        }

        @Override
        public void onNext(M model) {
            onSuccess(model);
        }

        @Override
        public void onComplete() {
            onFinish();
        }
    }
}

5:view,视图显示层

public class MainActivity extends BaseActivity implements PresenterCallback {
    @InjectView(R.id.text)
    TextView text;
    public Presenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        presenter=new Presenter(this);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                Map<String, String> params = new HashMap<>();
                params.put("loginame", "18821203006");
                params.put("password", "123456");
                presenter.getLoginData(params);
                break;
        }
    }

    @Override
    public void getDataSuccess(Object model) {
        LoginBean loginBean= (LoginBean) model;
        text.setText("identity: " + loginBean.content.identity + "\n"
                + "nickname: " + loginBean.content.nickname + "\n"
                + "loginame: " + loginBean.content.loginame + "\n"
                + "status: " + loginBean.hints.status);
    }

    @Override
    public void getDataFail(String msg) {
         ToastUtils.showToastView(this, "请求失败", Toast.LENGTH_SHORT);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.disposeRx();
        }
    }
}

本文结束,可直接使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值