1. 程式人生 > >Retrofit+Rxjava的聯用

Retrofit+Rxjava的聯用

新增依賴:

implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.x.y'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'//轉換器,請求結果轉換成Model
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'//配合Rxjava 使用

介面:

public interface JavaBeanService {
    
    @GET("dish_list.php?stage_id=1&limit=20&page=1")
    Observable<JavaBean> getResult();
}

程式碼:

        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.qubaobei.com/ios/cf/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        Observable<JavaBean> result = retrofit.create(JavaBeanService.class).getResult();
        result.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JavaBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(JavaBean javaBean) {
                        
                    }

                    @Override
                    public void onError(Throwable e) {
                       
                    }

                    @Override
                    public void onComplete() {

                    }
                });