3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RxJava2CallAdapterFactoryをaddしたRetrofit Clientで返り値Call型が指定されたAPI定義を実行するとどうなるか?

Last updated at Posted at 2020-09-11

こんな感じでRetorfit Clientを作成しているコードがあるとする。

val retrofitClient = Retrofit.Builder()
    .baseUrl(url)
    .client(okHttpClient)
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build()

addCallAdapterFactoryRxJava2CallAdapterを追加しているため、このクラインとでは次のようなObservable型を返すようなAPI定義を実行した際にレスポンスをObservableとして扱える。

 interface SmapleAPI {
     @GET("foo/bar")
     fun getSampleResponse(): Observable<Hoge>
 }

この時、次のCall型を返すようにAPI定義しRxJava2CallAdapterを追加したクライアントでAPIリクエストするとどうなるか?

 interface SmapleAPI {
     @GET("foo/bar")
     fun getSampleResponse(): Call<Hoge>
 }

この場合、APIリクエストするとCall型としてレスポンスを受け取れます。

RetrofitがCallAdapterをレスポンスに適用する流れ

addCallAdapterFactoryで渡されたクラス(CallAdapter.Factoryを継承したクラス)はRetrofitクラスのList<CallAdapter.Factory> callAdapterFactories変数に追加される。(callAdapterFactoriesにはデフォルトでDefaultCallAdapterFactoryが追加されている。)

そして、RetrofitクラスのnextCallAdapterメソッドでCallAdapter.FactoryからCallAdapterを得てそれがレスポンスに適用される。(HttpServiceMethodクラスのadaptとそれをoverrideした各クラスを参照)

この処理は次のnextCallAdapterコードで行っている。

int start = callAdapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
    CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
    if (adapter != null) {
        return adapter;
    }
}

ここで、CallAdapter.Factoryのgetメソッドの戻り値がnullとなる場合、nextCallAdapterメソッドはadapterを返さないのでレスポンスに適用されない。

そして、RxJava2CallAdapterFactoryのgetメソッドでは次のような判定を行い、rawTypeObservableFlowableSingleMaybe型でなければnullを返している。

そのため、nextCallAdapterメソッドでもRxJavaCallAddapterを返さず、レスポンスにRxJavaCallAddapterが適用されることは無い。

boolean isFlowable = rawType == Flowable.class;
boolean isSingle = rawType == Single.class;
boolean isMaybe = rawType == Maybe.class;
if (rawType != Observable.class && !isFlowable && !isSingle && !isMaybe) {
    return null;
}
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?