RxJava2和Retrofit

1.先导入包
implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

2.设置接口
public interface Test {
    @GET("user/getUserInfo")
    Observable get(@Query("uid") String uid);

}

3.具体代码
OkHttpClient client=new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();
Retrofit retrofit=new Retrofit.Builder()
         .baseUrl("http://120.27.23.105/")
         .addConverterFactory(GsonConverterFactory.create())
         .addCallAdapterFactory(RxJava2CallAdapterFactory.create())  //retrofit的初始化加了一行代码
         .client(client)  //添加拦截器
         .build();
  Test test = retrofit.create(Test.class);
  //被观察者
  Observable observable = test.get("uid");
  //观察者
  Observer observer=new Observer() {
      @Override
      public void onSubscribe(Disposable d) {

      }
      @Override
      public void onNext(ResponseBody responseBody) {
          System.out.println("成功");
      }

      @Override
      public void onError(Throwable e) {
          System.out.println("失败");
      }

      @Override
      public void onComplete() {

      }
  };
4.订阅
observable. subscribeOn(Schedulers.newThread()) //被观察者在哪里执行任务(调度主线程)
           .observeOn(Schedulers.newThread())//被观察者在哪里发送信息
           .subscribe(observer);  //订阅

你可能感兴趣的:(RxJava2和Retrofit)