Rxjava与Retrofit的结合:一

现在网络请求很流行使用他们的结合

首先添加依赖:

compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

创建网络返回数据的对象,如ResponseInfo
class ResponseInfo{
}
创建接口(我写的比较简单)
public interface Test2Api {
    @GET("myday05/a.json")
    Observable getTest();
}
网络请求代码
 retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://192.168.0.190:8989/")
                .build();
        // 创建网络请求接口的实例
        Test2Api test2Api = retrofit.create(Test2Api.class);
        observable = test2Api.getTest();
        subscribe = observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber() {
                    @Override
                    public void onCompleted() {
                        Log.e("www", "onCompleted ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("www", "onError = " + e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseInfo responseInfo) {
                        Log.e("www", "onNext = " + responseInfo.toString());
                    }
                });

你可能感兴趣的:(Rxjava与Retrofit的结合:一)