skip to content

Call Adapters & Coroutines

Call adapters that turn Retrofit's Call<T> into a suspend function, an RxJava type or your own result wrapper. A suspend API method looks like magic until you can name the layer that makes it work.

on this pageshow

explore

questions

6

In Retrofit 3, what may a suspend service method return, and why does Retrofit reject one declared to return Call<T>?

level: juniorimportance: must knowfreq 75%

answer

  1. three legal shapes, no adapter artifact
  2. body, Response wrapper, or nothing
  3. treated as if it returned Call<T>
  4. already asynchronous, so no nested Call

basics

~10 s

A Retrofit 3 suspend method returns the body type T, Response<T> when status and headers matter, or Unit to discard the body. Call<T> is rejected because a suspend method already runs its call asynchronously.

solid answer

~40 s

A `suspend` service method can return the deserialized body `T`, a `Response<T>` when the caller needs the status code and headers, or `Unit` when the body should be thrown away. Retrofit treats the method as if it returned `Call<T>`, enqueues that call and suspends until OkHttp answers, so it needs no extra adapter dependency and is safe to call from the main thread. A body-returning method throws `HttpException` for a non-2xx status, while `Response<T>` hands every HTTP response back to you. Declaring `suspend fun user(): Call<User>` would ask for a second, unexecuted call inside an already asynchronous one; since 2.10.0 Retrofit rejects that eagerly with a message telling you to return the body type instead.

code

kotlin · 18 lines
kotlin
import retrofit2.Response
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query

data class Order(val id: Long, val status: String)

interface OrdersApi {
    @GET("orders/{id}")
    suspend fun order(@Path("id") id: Long): Order

    @GET("orders")
    suspend fun ordersPage(@Query("cursor") cursor: String?): Response<List<Order>>

    @DELETE("orders/{id}")
    suspend fun cancelOrder(@Path("id") id: Long): Unit
}

go deeper

for a junior

Name the three return shapes, body, Response<T> and Unit, and say that a non-2xx status throws HttpException only when you asked for the body.

for a middle

Explain that Retrofit adapts a suspend method as Call<T>, enqueues it and resumes the coroutine, which is why no adapter artifact is needed and the main thread is safe.

for a senior

Know the edges: the eager rejection of suspend methods returning Call since 2.10.0, Unit versus Void for empty bodies, and that request serialization still runs on the calling thread.

for a principal

Be ready to set a team convention for when service methods return T versus Response<T>, so that header-driven and status-driven endpoints stay explicit.

## What a suspend method may return Since Retrofit 2.6.0 a service interface method can carry Kotlin's `suspend` modifier. Retrofit 3.0.0 keeps that support unchanged, and it is **built into the core artifact**: unlike RxJava or Guava return types, no extra `CallAdapter.Factory` has to be added to the `Retrofit.Builder`. | Declared return type | What the caller gets | Typical use | |---|---|---| | `T` (for example `Order`) | the converted body of a 2xx response | most reads and writes | | `Response<T>` | the full `retrofit2.Response`: `code()`, `headers()`, `body()`, `errorBody()` | pagination headers, ETags, branching on status | | `Unit` | nothing; the body is closed without being converted | a DELETE or a fire-and-forget POST | A method returning `T` throws `retrofit2.HttpException` when the status is outside 2xx, and a method returning `Response<T>` returns that response instead, so the caller checks `isSuccessful`. Both still throw an `IOException` for a transport failure; how an app sorts those outcomes into results is covered in the lesson on Retrofit's HTTP errors. ## What Retrofit does behind the scenes The suspend method is not magic; it is the ordinary `Call` machinery with a Kotlin bridge on top. When Retrofit parses the method it: 1. Notices the hidden `Continuation` parameter that the Kotlin compiler adds to every `suspend` function. 2. Reads the continuation's type argument. If it is `Response<T>`, it unwraps `T` and remembers that the caller wants the whole response. 3. Asks the call-adapter factories for an adapter for **`Call<T>`**, not for the declared type, and marks the method with `@SkipCallbackExecutor` so the Android main-thread hop is skipped. 4. On each invocation, builds an `OkHttpCall`, passes it through that adapter, and calls one of Retrofit's own Kotlin extensions: `await()`, its nullable and `Unit` variants, or `awaitResponse()`. 5. Those extensions call `Call.enqueue()` inside a cancellable continuation, then resume the coroutine with the body, the response or the exception. Because of step 3, a suspend method and a method returning `Call<T>` share the same adapter lookup, which is why a custom `CallAdapter.Factory` for suspend methods must recognise `Call<...>`. ## Why Call<T> is rejected A suspend method returning `Call<User>` would mean: suspend, perform an asynchronous call, and hand back yet another call that nobody has executed. That is never what the author wants. Retrofit 2.10.0 started rejecting it **eagerly**, when the method is parsed, with the message "Suspend functions should not return Call, as they already execute asynchronously" followed by the suggested return type. Parsing happens on the method's first invocation, or for every method at `create()` when the builder has `validateEagerly(true)`. ## Threading - The HTTP exchange runs on OkHttp's dispatcher threads, because the call is enqueued rather than executed. - Response conversion happens on that background thread too, inside `OkHttpCall`, before the coroutine resumes. - The coroutine resumes on the dispatcher it was called from, so a call made from `Dispatchers.Main` can update the UI directly afterwards. - Building the request, including serializing a `@Body` with most converters, runs on the calling thread; Retrofit 2.12.0 added a `withStreaming()` option to several first-party converters to defer that work. Wrapping a suspend Retrofit call in `withContext(Dispatchers.IO)` is therefore harmless but unnecessary. ## Choosing between the three - Return **`T`** when the caller only needs the data and treats every non-2xx as an error. - Return **`Response<T>`** when headers or specific status codes drive behaviour, such as a `Link` header for the next page or a 304 handled as "unchanged". - Return **`Unit`** for endpoints whose body the app does not read. Retrofit special-cases `Unit`; Java's `Void` makes the converter produce `null`, which a suspend method's non-null body check then rejects. ## Common mistakes - Keeping `Call<T>` return types and wrapping `execute()` in a coroutine, which blocks a thread and loses cancellation; declare the method `suspend` instead. - Adding a third-party coroutine call adapter left over from before 2.6.0; suspend support needs no factory at all. - Returning `T` and then needing a header, which the body type cannot carry; switch that one method to `Response<T>`. - Assuming `Response<T>` turns every failure into a value; transport and conversion failures still throw. ## Version notes `suspend` support arrived in 2.6.0, with `Response<T>` as an alternative return type from the start. `Unit` became a built-in body-discarding type in 2.5.0 and was broadened in 2.10.0. Retrofit 3.0.0 changed the OkHttp dependency to 4.12, not the suspend contract, and 3.x stays binary-compatible with libraries compiled against 2.x.

  • You already have a Call<T> from an older service method; how do you use it inside a coroutine?
    Retrofit ships Kotlin extensions on `Call`: `await()` returns the body and throws `HttpException` for a non-2xx status, and `awaitResponse()` returns the `Response<T>`. Both enqueue the call and cancel it if the coroutine is cancelled, so there is no need to wrap `execute()` in a background dispatcher.
  • Why does a suspend method returning Response<User> still throw in some cases?
    `Response<T>` only absorbs HTTP-level outcomes: any status code comes back as a response. A timeout, a refused connection or a dropped socket still throws an `IOException`, and a body the converter cannot parse throws from the converter. Turning those into results is a separate decision covered with Retrofit's error handling.
  • Is it safe to call a Retrofit suspend method from Dispatchers.Main?
    Yes. Retrofit enqueues the OkHttp call, so the network exchange and the response conversion happen on OkHttp's background threads, and the coroutine resumes on the main dispatcher afterwards. Only request building, including most converters' body serialization, runs on the calling thread.

  • A suspend Retrofit method should still return Call<T> and be awaited.
  • You must add a separate coroutine call adapter factory for suspend methods.
  • A suspend Retrofit call blocks its thread unless wrapped in withContext(Dispatchers.IO).
  • Returning Response<T> means the suspend method can never throw.
  • Endpoints without a body must return ResponseBody because Unit is not supported.

Assumes Retrofit 3.0.0; suspend methods date from 2.6.0, and the eager rejection of a suspend method returning Call arrived in 2.10.0.

open as a page

In Retrofit, how do Call.execute() and Call.enqueue() differ, and on which thread does each deliver its result on Android?

level: middleimportance: must knowfreq 65%

basics

~20 s

Call.execute() sends the request synchronously and returns a Response on the calling thread, so it must never run on Android's main thread. Call.enqueue() sends it on OkHttp's threads and, on Android, invokes the Callback on the main thread.

open as a page

In Retrofit, how does a service method's return type select a CallAdapter.Factory, and what happens when no registered factory accepts it?

level: middleimportance: should knowfreq 40%

basics

~20 s

Retrofit 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.

open as a page

With Retrofit's RxJava 3 adapter, how do create(), createSynchronous() and createWithScheduler() differ, and why can subscribeOn have no effect?

level: middleimportance: should knowfreq 42%

basics

~20 s

RxJava3CallAdapterFactory.create() enqueues each call on OkHttp's threads, so subscribeOn does not change where it runs. createSynchronous() executes on the subscribing thread, and createWithScheduler() executes on the given scheduler. None of them moves results to the main thread; observeOn does.

open as a page

When a coroutine awaiting a Retrofit suspend method is cancelled, how does that cancellation reach the HTTP request, and when does it not reach it?

level: seniorimportance: should knowfreq 33%

basics

~20 s

Retrofit awaits a suspend method's Call in a cancellable continuation that calls Call.cancel() when the coroutine is cancelled, which cancels the underlying OkHttp call. It does not reach a blocking Call.execute() inside withContext, nor an enqueued Call nobody cancels.

open as a page

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%

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.

open as a page