In Retrofit, how does a service method's return type select a CallAdapter.Factory, and what happens when no registered factory accepts it?
answer
- an ordered list, first match wins
- added factories before built-in ones
- get() returns null to decline
- Could not locate call adapter
basics
~20 sRetrofit asks each CallAdapter.Factory in order, the ones you added first and its built-in ones last, and uses the first whose get() returns non-null. If none accepts the type, the method fails with an IllegalArgumentException naming the type and every factory tried.
solid answer
~40 sWhen Retrofit parses a service method it calls `get(returnType, annotations, retrofit)` on each registered `CallAdapter.Factory` in order: factories added with `addCallAdapterFactory()` in the order you added them, then the built-in ones (`DefaultCallAdapterFactory` for `Call`, plus a `CompletableFuture` factory on the JVM and on Android API 24+). A factory returns `null` to decline, and the first non-null adapter wins, so order matters when two factories could claim the same type. For a `suspend` method the type asked about is `Call<T>`, not the declared one. If nobody accepts, Retrofit throws `IllegalArgumentException`: "Unable to create call adapter for ..." caused by "Could not locate call adapter for ..." listing the factories tried. That happens on the method's first invocation, or at `create()` with `validateEagerly(true)`.
code
kotlin · 19 linesimport io.reactivex.rxjava3.core.Scheduler
import io.reactivex.rxjava3.core.Single
import java.lang.reflect.Type
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Retrofit
// Register BEFORE RxJava3CallAdapterFactory: the first non-null adapter wins.
class ObserveOnSingleFactory(private val scheduler: Scheduler) : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
if (getRawType(returnType) != Single::class.java) return null
@Suppress("UNCHECKED_CAST")
val delegate = retrofit.nextCallAdapter(this, returnType, annotations) as CallAdapter<Any, Single<*>>
return object : CallAdapter<Any, Single<*>> {
override fun responseType(): Type = delegate.responseType()
override fun adapt(call: Call<Any>): Single<*> = delegate.adapt(call).observeOn(scheduler)
}
}
}go deeper
Recall that return types other than Call need a factory added with addCallAdapterFactory, and that a missing one fails with Could not locate call adapter.
Explain the ordered lookup: your factories first, built-ins last, null to decline, first non-null wins, cached per method, and suspend methods looked up as Call<T>.
Diagnose ordering bugs: a decorator registered after the RxJava factory, a broad Call factory swallowing suspend methods, and lazy failures that validateEagerly would surface early.
Decide how many custom adapters a codebase should tolerate, and require validateEagerly in tests so adapter wiring cannot fail first in production.
## The lookup A **call adapter** turns Retrofit's internal `Call<R>` into whatever type the service method declares: a `Call<R>` itself, an RxJava `Single<R>`, a `CompletableFuture<R>`, or your own wrapper. A **`CallAdapter.Factory`** decides, from the method's return type, whether it can produce such an adapter. The lookup for one method goes like this: 1. Retrofit determines the **adapter type**. For a normal method it is the generic return type, for example `Single<Profile>`. For a `suspend` method it is `Call<T>`, built from the continuation's type, with `T` unwrapped from `Response<T>` when needed. 2. It walks the factory list from the start and calls `get(returnType, annotations, retrofit)` on each. 3. The first factory that returns a non-null `CallAdapter` wins; the rest are never asked. 4. Retrofit then reads `adapter.responseType()`, the body type such as `Profile`, and looks up a **converter** for it. 5. The resulting service method is cached, so a successful lookup happens once per method, not once per call. ## The factory list order `Retrofit.Builder.build()` assembles the list as follows. | Position | Factory | Handles | |---|---|---| | first | each factory passed to `addCallAdapterFactory()`, in the order added | whatever their `get()` accepts | | then, on the JVM and Android API 24+ | the built-in `CompletableFuture` factory | `CompletableFuture<T>` | | last | `DefaultCallAdapterFactory` | `Call<T>`, including the `Call<T>` behind suspend methods | Because your factories come first, a custom factory can claim `Call<Something>` before the default one sees it, which is exactly how result-wrapping adapters for suspend methods work. It also means a factory that claims too broadly, say every `Call`, silently takes over every suspend method in the service. ## What get() receives - **`returnType`**: the adapter type from step 1, with full generic information. Factories use the protected helpers `getRawType()` and `getParameterUpperBound()` to inspect it. - **`annotations`**: the method's annotations. Suspend methods also carry `@SkipCallbackExecutor`, which Retrofit adds itself. A factory can define its own annotation to switch behaviour per method. - **`retrofit`**: the instance, which gives access to `nextCallAdapter()` and to converters. Returning `null` means "not mine". Throwing an exception means "mine, but declared wrongly"; the RxJava 3 factory does this for a raw `Single` with no type argument. ## When the error appears If every factory returns `null`, `nextCallAdapter()` throws `IllegalArgumentException` with a message such as "Could not locate call adapter for io.reactivex.rxjava3.core.Single<Profile>." followed by a "Tried:" list of factory class names. Retrofit wraps it as "Unable to create call adapter for ..." plus "for method ProfileApi.meRx". The classic cause is declaring an RxJava return type and forgetting `addCallAdapterFactory(RxJava3CallAdapterFactory.create())`. - By default the failure surfaces **on the first invocation** of that method, often far from where the `Retrofit` instance was built. - `Retrofit.Builder.validateEagerly(true)` makes `create()` parse every method up front, so a debug build or a unit test fails immediately. - Failures are not cached: each later invocation parses the method again and throws the same error. ## Decorating with nextCallAdapter A factory does not have to build an adapter from scratch. `retrofit.nextCallAdapter(this, returnType, annotations)` asks the factories **after** `this` one for an adapter, so a factory can wrap whatever the next one produces. A common example adds `observeOn` to every RxJava `Single`; it only works if the decorating factory is registered **before** the RxJava 3 factory, because the first non-null answer wins and the RxJava factory would never return `null` for a `Single`. ## Factories you are likely to meet - `RxJava3CallAdapterFactory` from `adapter-rxjava3`, for `Observable`, `Flowable`, `Single`, `Maybe` and `Completable`. - The Guava adapter from `adapter-guava`, for `ListenableFuture`. - The built-in `CompletableFuture` support, which replaced the deprecated `adapter-java8` artifact in 2.5.0. - Your own factories, such as a result-wrapping adapter for suspend methods or a decorator around another adapter's output. Kotlin `suspend` methods need none of them: unless a custom factory claims their `Call<T>`, they are served by `DefaultCallAdapterFactory`. ## Pitfalls - Registering two factories that both accept a type and assuming the later one applies. - Writing a factory that checks for the declared wrapper type when the methods are `suspend`, where it is only ever asked about `Call<...>`. - Forgetting that a type handled by your own factory no longer goes through `DefaultCallAdapterFactory`, so the Android main-thread callback executor no longer applies to it.
- How can you make a missing call adapter fail at startup or in a test instead of on first use?Build Retrofit with `validateEagerly(true)`. Then `create()` parses every non-default, non-static method of the interface and throws the same `IllegalArgumentException` immediately. Many teams enable it in debug builds or in a unit test that creates each service, and leave it off in release to avoid the startup reflection cost.
- Why does a custom factory that claims every Call<T> break code that was working?Your factories are consulted before `DefaultCallAdapterFactory`, and suspend methods are looked up as `Call<T>`, so the broad factory now handles every plain `Call` method and every suspend method. Anything the default adapter did, such as the Android main-thread callback hop for `Call.enqueue`, is lost unless your factory delegates through `nextCallAdapter()`.
A hotel front desk with several concierges in a fixed line: each guest's request goes to the first, who either takes it or passes it on, and the first one who says yes handles it, even if a better specialist stands further down the line.
- The last factory added with addCallAdapterFactory takes priority.
- Retrofit picks a call adapter fresh on every call to the method.
- A factory signals it cannot handle a type by throwing an exception.
- A suspend method's factory is asked about the declared return type.
- A missing call adapter fails when the Retrofit instance is built.