Android 响应式编程框架 - RxJava2(三)RxJava2+Retrofit 2获取网络数据

本文主要让大家知道RxJava2+Retrofit 2获取网络数据简单方法,如果有不了解RxJava和Retrofit请先去学习了在来阅读。

我将以下面的图片作为栗子为大家展现RxJava2+Retrofit 2简单获取网络数据

一、添加依赖
  // RxJava2.0
    implementation 'io.reactivex.rxjava2:rxjava:2.0.1'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.google.code.gson:gson:2.2.4'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'// retrofit+gson
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' // Rxjava与Retrofit结合使用必须添加这个依赖
    compile 'com.github.bumptech.glide:glide:4.6.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
    //banner
    implementation 'com.youth.banner:banner:1.4.10' 
二、创建依赖接口(创建观察者)和Bean
public class OneBean {
    private List data;

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }
    public static class DataBean {
        private String desc;
        private int id;
        private String imagePath;
        private int isVisible;
        private int order;
        private String title;
        private int type;
        private String url;

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getImagePath() {
            return imagePath;
        }

        public void setImagePath(String imagePath) {
            this.imagePath = imagePath;
        }

        public int getIsVisible() {
            return isVisible;
        }

        public void setIsVisible(int isVisible) {
            this.isVisible = isVisible;
        }

        public int getOrder() {
            return order;
        }

        public void setOrder(int order) {
            this.order = order;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}
public interface Api {
    //1.创建观察者
    @GET("banner/json")
    Observable getBannerRequest();
三、创建Retrofit
  Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//创建Retrofit和RxJava关联
                .addConverterFactory(GsonConverterFactory.create())//创建Gson解析
                .build();
四、创建动态代理
Api api = retrofit.create(Api.class);
五、关联订阅
 api.getBannerRequest().subscribeOn(Schedulers.io())//订阅事件触发IO
        .observeOn(AndroidSchedulers.mainThread())//在主线程处理返回事件
        .subscribe(new Observer() {//订阅
            @Override
            public void onSubscribe(Disposable d) {
                //取消订阅
                Log.e(TAG,"----------onSubscribe");
            }

            @Override
            public void onNext(OneBean value) {
                list.addAll(value.getData());
                //向下执行
                Log.e(TAG,"----------onNext"+value.toString());

            }

            @Override
            public void onError(Throwable e) {
                //抛异常触发
                Log.e(TAG,"----------onError");

            }

            @Override
            public void onComplete() {
            //设置banner
                for (OneBean.DataBean imgUrl:list) {
                    imgViewUrl.add(imgUrl.getImagePath());
                    titles.add(imgUrl.getTitle());
                }
                //设置图片加载器
                banner.setImageLoader(new GlideImageLoader());
                //设置banner样式
                banner.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);
                //设置banner动画效果
                banner.setBannerAnimation(Transformer.DepthPage);
                //设置标题集合(当banner样式有显示title时)
                banner.setBannerTitles(titles);
                //设置图片集合
                banner.setImages(imgViewUrl);
                //设置自动轮播,默认为true
                banner.isAutoPlay(true);
                //设置轮播时间
                banner.setDelayTime(1500);
//                //设置指示器位置(当banner模式中有指示器时)
//                    banner.setIndicatorGravity(BannerConfig.CENTER);
                //banner设置方法全部调用完毕时最后调用
                banner.start();
                //完成时
                Log.e(TAG,"----------onComplete");

            }
        });
六、RxJava2+Retrofit 2简单封装
public class RequestManager  {
    public  Retrofit mRetrofit ;
    public RequestApi requestApi;
//    private Context mContext;

    public RequestManager() {
        mRetrofit = createRetrofit();
        requestApi = networkApi(RequestApi.class);
//        this.mContext = mContext;
    }

    //1.创建匿名内部内单利
    public static class RequestManagerHolder{
        public static RequestManager instance = new RequestManager();
    }
    public static RequestManager getInstance() {
        return RequestManagerHolder.instance;
    }

    //动态代理
    public  T networkApi(Class api){
        return mRetrofit.create(api);
    }

    //2.创建Retrofit网络请求
    private Retrofit createRetrofit() {
        return new Retrofit.Builder().baseUrl(Constant.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//关联RxJava2
                .addConverterFactory(GsonConverterFactory.create())//创建Gson解析
                .client(HttpClient())
                .build();
    }

    /**
     * 每次请求都会走拦截器,即:可以动态修改header
     */
    private OkHttpClient HttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (Constant.LOG_TYPE) {
            // OkHttp日志拦截器
            builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
//        builder.addInterceptor(chain -> {
//            Request original = chain.request();
//            Request request = original.newBuilder()
//                    // 设置请求头
//                    .header("XX-Token", SPUtils.getInstance().getString("token", ""))
//                    .header("XX-Device-Type", "android")
//                    .method(original.method(), original.body())
//                    .build();
//            return chain.proceed(request);
//        });
        return builder.build();
    }
}

增加依赖

  implementation 'com.squareup.okhttp3:okhttp:3.9.0'
  implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
小结:

发现Retrofit搭配RxJava之后,绝对是最好用的网络请求库,如有问题,欢迎留言指正

你可能感兴趣的:(Android)