skip to content

When you write a Retrofit CallAdapter.Factory so suspend methods return a sealed ApiResult<T> instead of throwing, what type does the factory receive, and what must the adapter return?

level: seniorimportance: should knowfreq 38%

answer

  1. suspend hides the real lookup type
  2. Call<ApiResult<T>>, not ApiResult<T>
  3. responseType is the inner body
  4. a delegating Call that always succeeds

basics

~20 s

For suspend fun user(): ApiResult<User>, the factory is asked about Call<ApiResult<User>>. It must return a CallAdapter whose responseType() is User and whose adapt() returns a delegating Call<ApiResult<User>> that always reports a successful Response holding the wrapped outcome.

solid answer

~40 s

Retrofit adapts every `suspend` method as `Call<T>`, so a factory checking for a raw `ApiResult` never matches; it must accept `Call<ApiResult<X>>`, dig out `X` with `getParameterUpperBound()`, and return a `CallAdapter<X, Call<ApiResult<X>>>` whose `responseType()` is `X` so the right converter is chosen. `adapt()` wraps the original call in your own `Call<ApiResult<X>>` whose `enqueue()` delegates and turns every outcome, success, non-2xx or `onFailure`, into `callback.onResponse(this, Response.success(result))`. Retrofit's internal `await()` then sees a successful response with a non-null body and resumes the coroutine with your `ApiResult` instead of throwing. The wrapper must forward `cancel()`, `isCanceled()`, `request()` and `timeout()`, and `clone()` must wrap `delegate.clone()`, or coroutine cancellation stops reaching OkHttp.

code

kotlin · 63 lines
kotlin
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import okhttp3.Request
import okio.Timeout
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit

sealed interface ApiResult<out T> {
    data class Success<T>(val value: T) : ApiResult<T>
    data class HttpError(val code: Int) : ApiResult<Nothing>
    data class Failure(val error: Throwable) : ApiResult<Nothing>
}

class ApiResultCallAdapterFactory : CallAdapter.Factory() {
    override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
        if (getRawType(returnType) != Call::class.java) return null
        val callType = getParameterUpperBound(0, returnType as? ParameterizedType ?: return null)
        if (getRawType(callType) != ApiResult::class.java) return null
        val bodyType = getParameterUpperBound(0, callType as? ParameterizedType ?: return null)
        return ApiResultCallAdapter<Any>(bodyType)
    }
}

private class ApiResultCallAdapter<T : Any>(private val bodyType: Type) : CallAdapter<T, Call<ApiResult<T>>> {
    override fun responseType(): Type = bodyType
    override fun adapt(call: Call<T>): Call<ApiResult<T>> = ApiResultCall(call)
}

private class ApiResultCall<T : Any>(private val delegate: Call<T>) : Call<ApiResult<T>> {
    override fun enqueue(callback: Callback<ApiResult<T>>) {
        delegate.enqueue(object : Callback<T> {
            override fun onResponse(call: Call<T>, response: Response<T>) {
                callback.onResponse(this@ApiResultCall, Response.success(toResult(response)))
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                callback.onResponse(this@ApiResultCall, Response.success<ApiResult<T>>(ApiResult.Failure(t)))
            }
        })
    }

    private fun toResult(response: Response<T>): ApiResult<T> {
        val body = response.body()
        return when {
            !response.isSuccessful -> ApiResult.HttpError(response.code())
            body != null -> ApiResult.Success(body)
            else -> ApiResult.Failure(IllegalStateException("HTTP ${response.code()} had no body"))
        }
    }

    override fun execute(): Response<ApiResult<T>> =
        throw UnsupportedOperationException("ApiResultCall is for suspend methods, which use enqueue()")

    override fun clone(): Call<ApiResult<T>> = ApiResultCall(delegate.clone())
    override fun cancel() = delegate.cancel()
    override fun isCanceled(): Boolean = delegate.isCanceled()
    override fun isExecuted(): Boolean = delegate.isExecuted()
    override fun request(): Request = delegate.request()
    override fun timeout(): Timeout = delegate.timeout()
}

go deeper

for a junior

Recall that a CallAdapter.Factory is how Retrofit learns new return types, and that suspend methods go through the same mechanism.

for a middle

Explain that a suspend method is looked up as Call<T>, so a result adapter must accept Call<ApiResult<T>> and report the inner body type as responseType.

for a senior

Build the delegating Call correctly: always a successful Response, cancel and clone forwarded, onFailure mapped, and explain why Response.error would be turned back into HttpException.

for a principal

Decide whether a custom adapter or a plain helper should carry the app-wide result type, weighing enforcement at the interface against custom plumbing everyone must maintain.

## Why the factory sees Call<...> A **sealed result type**, here `ApiResult<T>` with cases such as `Success`, `HttpError` and `Failure`, lets callers handle outcomes with a `when` instead of `try`/`catch`. Retrofit has no built-in support for it, so the usual tool is a custom `CallAdapter.Factory`. The trap is that, for a `suspend` method, Retrofit never asks factories about the declared type. When it parses `suspend fun user(): ApiResult<User>` it: 1. Reads the Kotlin `Continuation` parameter and finds the result type `ApiResult<User>`. 2. Builds the adapter type **`Call<ApiResult<User>>`** and asks each factory for an adapter for it. 3. Reads the adapter's `responseType()` and looks up a converter for that type. 4. On each invocation, passes its own `OkHttpCall` to `adapt()`, then awaits the returned `Call` through `enqueue()`. 5. Resumes the coroutine with the response body if the response is successful and the body is non-null; otherwise it throws, an `HttpException` for a non-2xx status. So the adapter's job is to return a `Call` whose responses are **always** successful and whose body is **always** your `ApiResult`. ## The factory - Return `null` unless `getRawType(returnType)` is `Call::class.java`. - Take the `Call`'s type argument with `getParameterUpperBound(0, ...)` and return `null` unless its raw type is `ApiResult`. - Take `ApiResult`'s own type argument, for example `User`, and use it as `responseType()`. If you returned `ApiResult<User>` there, the converter would be asked to deserialize the body as an `ApiResult`, which is not the shape the server sends. - Register the factory with `addCallAdapterFactory()`; custom factories are consulted before `DefaultCallAdapterFactory`, so yours wins for `Call<ApiResult<...>>` and declines everything else. ## The wrapping Call | Method | What the wrapper does | |---|---| | `enqueue(callback)` | delegates, maps the outcome to an `ApiResult`, always calls `callback.onResponse(this, Response.success(result))` | | `execute()` | unused by suspend methods; implement it the same way or throw if the type is suspend-only | | `cancel()`, `isCanceled()` | forward to the delegate | | `clone()` | returns a new wrapper around `delegate.clone()` | | `isExecuted()`, `request()`, `timeout()` | forward to the delegate | Which outcome becomes which case, for example whether a 2xx with an empty body is a success, and how an error body is parsed into `HttpError`, is a separate design decision covered in the lesson on Retrofit's HTTP errors. The adapter only has to deliver whatever result that mapping produces. ## Cancellation and cloning Retrofit awaits the wrapper inside a cancellable continuation that calls `cancel()` on it when the coroutine is cancelled. If the wrapper does not forward `cancel()` to the delegate, the OkHttp request keeps running after the screen is gone. When cancellation does reach OkHttp, the delegate's `onFailure` fires with an `IOException`, and your wrapper turns it into a `Failure` result; that is harmless, because the cancelled continuation has already resumed with a `CancellationException` and ignores the late result. The adapter therefore does not swallow coroutine cancellation. `clone()` matters less for suspend methods but is part of the `Call` contract; returning `this`, or a clone of the delegate without the wrapper, breaks any code that retries by cloning. ## Wiring it up 1. Register the factory with `addCallAdapterFactory(ApiResultCallAdapterFactory())`, next to any other factories the app uses. 2. Declare service methods as `suspend fun user(@Path("id") id: Long): ApiResult<User>`. 3. Call them without `try`/`catch` and branch with `when (val result = api.user(id))` over the sealed cases. 4. Leave coroutine cancellation alone: it never reaches the wrapper's callbacks as a `CancellationException`, because Retrofit resumes the coroutine with it directly. ## Pitfalls - Matching `ApiResult` directly: this works for a non-suspend `fun user(): ApiResult<User>`, but such an adapter would have to block in `execute()`, and it never matches suspend methods. - Returning `Response.error(...)` from the wrapper for HTTP failures: `await()` would turn it back into an `HttpException`, defeating the point. - Forgetting that a type your factory handles no longer passes through `DefaultCallAdapterFactory`. For suspend methods that is fine, because they skip the callback executor anyway, but a non-suspend `Call<ApiResult<T>>` method would now call back on an OkHttp thread on Android. - Catching too little: `onFailure` carries both `IOException` for the network and runtime exceptions from the converter, so the mapping must decide what each becomes. Testing the adapter is straightforward with a mock web server: enqueue a 200, a 404 and a dropped connection, and assert the three `ApiResult` cases.

  • Does this adapter stop a cancelled coroutine from seeing a CancellationException?
    No. Retrofit awaits the wrapper in a cancellable continuation, so on cancellation the coroutine resumes with `CancellationException` straight away and Retrofit calls `cancel()` on the wrapper. The `Failure` result produced later by the cancelled OkHttp call reaches a continuation that has already completed and is ignored, provided the wrapper forwards `cancel()`.
  • Why not keep suspend methods returning T and catch exceptions in a helper function instead?
    A small `runCatching`-style helper in the repository is simpler and keeps Retrofit's defaults, but every call site has to remember it. The adapter makes the result type part of the service interface, so it cannot be forgotten, at the cost of custom `Call` plumbing that must forward cancellation correctly and that new team members have to understand.

  • For suspend methods the factory should match getRawType(returnType) == ApiResult::class.java.
  • responseType() should return ApiResult<User> so the converter wraps it.
  • The wrapper can report HTTP errors with Response.error and Retrofit will wrap them.
  • The wrapping Call does not need to forward cancel() because coroutines handle it.
  • A custom result adapter swallows coroutine cancellation into a Failure result.