RxJava2.0+Retrofit请求网络数据

本文只做简单步骤以作记录.

1.添加依赖

// RxJava2.0
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
// Retrofit
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'// retrofit+gson
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' // Rxjava与Retrofit结合使用必须添加这个依赖

2.创建Builder,配置信息

Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(Api.SERVER_IP);
builder.addConverterFactory(GsonConverterFactory.create());
//设置Adapter  
//不设置这个会报错:Could not locate call adapter for io.reactivex.Observable>
builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create());

3.构建Retrofit对象

    Retrofit retrofit = builder.build();

4.配置参数和链接

public interface ApiInfo{
    @POST(Api.GetCarBrand)
    Observable getCarBrand();// 这里类型为Observable,泛型为JavaBean
}

5.发起请求

 ApiInfo api = retrofit.create(ApiInfo.class);
    Observable observable = api.getCarBrand();
    observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer() {
                @Override
                public void onSubscribe(Disposable d) {
                    progressBar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onNext(BrandResponse brand) {

                    Log.e("ende","onNext:"+brand.toString());
                }



                @Override
                public void onError(Throwable e) {
                    progressBar.setVisibility(View.GONE);
                    Log.e("ende","onError:"+e.toString());
                }

                @Override
                public void onComplete() {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(TowActivity.this,"请求完成",Toast.LENGTH_SHORT).show();
                }
            });

6.请求结果

 onNext:BrandResponse{msg='', status=0, success=true, data=[DataBean{carBrandNm='宝马', carBrandNo='10'}, DataBean{carBrandNm='奔驰', carBrandNo='11'}, DataBean{carBrandNm='长城', carBrandNo='12'}]}

你可能感兴趣的:(RxJava2.0+Retrofit请求网络数据)