Retrofit2源码解析(三)添加 RxJavaCallAdapterFactory适配器

1、获取实例时,我们再添加一个适配器

        retrofit = new Retrofit.Builder().baseUrl("http://localhost:8080/campus/")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .build();

老规则,这里只是添加了一个适配器,所以上面两篇的返回类型还是支持的。

看下RxJavaCallAdapterFactory的源码,代码比较多,但我们只需要看 CallAdapter

retrofit2.adapter.rxjava.RxJavaCallAdapterFactory.java

//支持返回类型为rx.Observable、rx.Single、rx.Completable
//根据不同的类型生成对应的CallAdapter的实现类
  @Override
  public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
    Class rawType = getRawType(returnType);
    String canonicalName = rawType.getCanonicalName();
    boolean isSingle = "rx.Single".equals(canonicalName);
    boolean isCompletable = "rx.Completable".equals(canonicalName);
    if (rawType != Observable.class && !isSingle && !isCompletable) {
      return null;
    }
    if (!isCompletable && !(returnType instanceof ParameterizedType)) {
      String name = isSingle ? "Single" : "Observable";
      throw new IllegalStateException(name + " return type must be parameterized"
          + " as " + name + " or " + name + "");
    }

    if (isCompletable) {
      return CompletableHelper.createCallAdapter(scheduler);
    }

    CallAdapter> callAdapter = getCallAdapter(returnType, scheduler);
    if (isSingle) {
      return SingleHelper.makeSingle(callAdapter);
    }
    return callAdapter;
  }

所以再在可以将接口改成如下

    public interface HttpLoginRx {
        @POST("account/login")
        Observable<HashMap<String, Object>> login(@Body Account account);
    }

也是ok的。

你可能感兴趣的:(源码,java,Retrofit2,java)