RxJava+Retrofit 在项目中的使用

简介:RxJava是一个基于事件流,实现异步操作的库

使用方式:基于事件流的链式调用

原理:基于一种扩展的观察者模式

Observable(被观察者)、Observer(观察者)、subscribe(订阅)

在项目中的使用

一、在gradle中添加如下配置

implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'io.reactivex:rxjava:1.2.6'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

二、Retrofit接口定义,如下

public interface RetrofitInterface {

    @FormUrlEncoded
    @POST("")
    Observable<TheBean> getData(
            @Field("id")String theId,
            @Field("page")String thePage);
}

三、创建APIService实例,如下

public class APIService {

    private RetrofitInterface retrofitInterface;
    private static APIService apiService;

    //获取APIService的单例
    public static APIService getInstence() {
        if (apiService == null) {
            synchronized (APIService.class) {
                if (apiService == null) {
                    apiService = new APIService();
                }
            }
        }
        return apiService;
    }

    //封装配置API
    public RetrofitInterface getDailyService() {
        if (retrofitInterface == null) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ConstantsData.URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
            //创建完成
            retrofitInterface = retrofit.create(RetrofitInterface.class);
        }
        return retrofitInterface;
    }
}

四、使用,如下

APIService.getInstence().getDailyService().getData("1", "1").subscribeOn(Schedulers.io())//在子线程请求数据
        .observeOn(Schedulers.io())  //请求完成后子线程中执行
        .doOnNext(new Action1<TheBean>() {
            @Override
            public void call(TheBean theBean) {
                //例如存储数据的操作
            }
        })
        .observeOn(AndroidSchedulers.mainThread())//在主线程显示数据
        .subscribe(new Subscriber<TheBean>() {
            @Override
            public void onCompleted() {
                //请求完成
            }

            @Override
            public void onError(Throwable throwable) {
                //请求错误
            }

            @Override
            public void onNext(TheBean theBean) {
                //请求成功,在此处理
            }
        });

猜你喜欢

转载自blog.csdn.net/QiY6010/article/details/83542578