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 + "<Foo> or " + name + "<? extends Foo>");
    }

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

    CallAdapter<Observable<?>> 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的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章