RxJava2.0+Retrofit要求ネットワークデータ

2585 ワード

本稿では、記録のための簡単な手順のみを行う.
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'}]}