Android Retrofit2+Rxjava2的使用

之前写过一篇这样的博客,当时初学理解不够透彻,写法比较不实用。开发过程中,渐渐学习到了正确的使用方式,在这里简单记录一下

需要引入的包

			//rxjava
            "rxjava"     : 'io.reactivex.rxjava2:rxjava:2.1.12',
            //rxandroid
            "rxandroid"  : 'io.reactivex.rxjava2:rxandroid:2.0.2',
            //retrofit
            "retrofit"   : 'com.squareup.retrofit2:retrofit:2.4.0',
            //converter-gson retrofit的gson转换器
            "converter"  : 'com.squareup.retrofit2:converter-gson:2.4.0',
            //retrofit2-rxjava2-adapter
            "adapter"    : 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0',
            //okhttp3:logging-interceptor
            "interceptor": 'com.squareup.okhttp3:logging-interceptor:3.9.1'

建立serviceapi类 存放所有请求
就不在贴代码了

HttpHelper代码(主要比之前增加了单例模式,以及不用每个请求写一个方法)

public class HttpHelper {

    static HttpHelper httpHelper;
    
    public static HttpHelper getInstance(){
        if (httpHelper == null){
            synchronized (HttpHelper.class){
                if(httpHelper == null){
                    httpHelper = new HttpHelper();
                }
            }
        }
        return httpHelper;
    }

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(2, TimeUnit.MINUTES)
            .writeTimeout(2, TimeUnit.MINUTES)
            .readTimeout(2, TimeUnit.MINUTES)
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(SpUtils.getInstance().getBaseUrl())//基地址
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();

    ApiService serviceApi = retrofit.create(ApiService.class);

    public ApiService getServiceApi(){
        return retrofit.create(ApiService.class);
    }

}

使用的方法也略有改变

HttpHelper.getInstance()
                .getServiceApi()
                .getData(map)//serviceapi接口中的请求
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {//匿名写法也有改变
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("onSubscribe",""+d.toString());
                    }

                    @Override
                    public void onNext(PushClientBean bean) {
                        Log.e("onNext",""+bean.toString());

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("onError",""+e.toString());
                    }

                    @Override
                    public void onComplete() {
                        Log.e("onComplete","onComplete");
                    }
                });

你可能感兴趣的:(Android开发记录)