In Retrofit, how do Call.execute() and Call.enqueue() differ, and on which thread does each deliver its result on Android?
answer
- blocking versus callback
- Android's callback executor
- a main-Looper Handler
- one-shot call, clone to repeat
basics
~20 sCall.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.
solid answer
~40 s`execute()` blocks the calling thread until the response arrives and returns a `Response<T>`, throwing `IOException` if the server could not be reached; on Android that thread must be a background one. `enqueue(callback)` returns immediately: OkHttp's dispatcher runs the exchange, Retrofit converts the body on that background thread, and then Retrofit's callback executor delivers the result. On Android the default executor posts to the main `Looper`, so `onResponse` and `onFailure` run on the main thread; on the plain JVM they run on the background thread. `onResponse` fires for every HTTP response, including a 500, so you still check `isSuccessful`, while `onFailure` is for network and unexpected errors. Either way a `Call` is single-use: a second `execute()` or `enqueue()` throws `IllegalStateException`, and `clone()` gives a fresh copy.
code
kotlin · 30 linesimport retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.http.GET
data class Order(val id: Long, val status: String)
interface LegacyOrdersApi {
@GET("orders")
fun orders(): Call<List<Order>>
}
// Background threads only: execute() blocks until the response arrives.
fun loadBlocking(api: LegacyOrdersApi): List<Order> {
val response = api.orders().execute()
return if (response.isSuccessful) response.body().orEmpty() else emptyList()
}
// Any thread: enqueue() returns at once; on Android the callback runs on the main thread.
fun loadAsync(api: LegacyOrdersApi, show: (List<Order>) -> Unit, fail: (String) -> Unit) {
api.orders().enqueue(object : Callback<List<Order>> {
override fun onResponse(call: Call<List<Order>>, response: Response<List<Order>>) {
if (response.isSuccessful) show(response.body().orEmpty()) else fail("HTTP ${response.code()}")
}
override fun onFailure(call: Call<List<Order>>, t: Throwable) {
if (!call.isCanceled) fail(t.message ?: "request failed")
}
})
}go deeper
Remember: execute blocks and belongs on a background thread; enqueue is asynchronous and its callback lands on the main thread on Android.
Explain the path of an enqueued call: OkHttp thread, conversion on that thread, then the callback executor's main-thread hop, and why onResponse still needs isSuccessful.
Show you know the knobs and traps: one-shot calls and clone, @SkipCallbackExecutor, a custom callbackExecutor, and that other adapters ignore the executor entirely.
Explain why a team moving to suspend methods keeps Call only at legacy edges, and what the callback-executor default means for code shared with JVM modules.
## The Call object A non-suspend Retrofit service method that returns `Call<T>` does not touch the network when you call it. It returns a **`retrofit2.Call<T>`**, a description of one HTTP request plus its response type, built by Retrofit's built-in `DefaultCallAdapterFactory`. Nothing happens until you run it: - **`execute()`** runs it synchronously. - **`enqueue(Callback<T>)`** runs it asynchronously. - **`cancel()`** stops it, whether it is running or not yet started. - **`clone()`** makes a new, identical call that can be run again. - **`isExecuted()`**, **`isCanceled()`**, **`request()`** and **`timeout()`** inspect it. ## execute(): synchronous `execute()` sends the request on the thread that calls it and returns a `Response<T>` once the body has been converted. - It **blocks** that thread for the whole exchange: DNS, connect, upload, server time, download. - It throws `IOException` when the server cannot be reached or the exchange breaks, and a `RuntimeException` when building the request or converting the response fails. - A non-2xx status is **not** an exception: it comes back as a `Response` whose `isSuccessful` is false. - On Android it must never run on the main thread. The platform throws `NetworkOnMainThreadException` when the main thread does network I/O, and even where it did not, the UI would freeze. `execute()` fits code that is already on a worker thread, such as a background job or a unit test. ## enqueue(): asynchronous `enqueue()` returns at once. The sequence for one call is: 1. Retrofit builds the OkHttp request on the calling thread, which includes serializing a `@Body` with most converters. 2. OkHttp's dispatcher runs the exchange on one of its own threads. 3. On that same background thread Retrofit converts the response body with the configured converter. 4. Retrofit hands the finished `Response<T>`, or the failure, to its **callback executor**. 5. The executor invokes `onResponse(call, response)` or `onFailure(call, throwable)`; exactly one of them runs per call. `onResponse` means "an HTTP response arrived", not "the request succeeded": a 404 or a 500 lands there too. `onFailure` is reserved for network failures and unexpected errors while creating the request or processing the response. ## Where callbacks run | Environment | Default callback executor | Where `onResponse` and `onFailure` run | |---|---|---| | Android | a `Handler` on the main `Looper` | the main thread | | Plain JVM | none | the OkHttp background thread that made the call | | Any, with `Retrofit.Builder.callbackExecutor(executor)` | your executor | wherever that executor runs tasks | | Any, method annotated `@SkipCallbackExecutor` | bypassed | the OkHttp background thread | The callback executor applies only to methods returning `Call`. Return types handled by another adapter, such as the RxJava 3 adapter, ignore it and deliver on the thread their own rules dictate. ## One-shot calls and clone() A `Call` can be run once. A second `execute()` or `enqueue()` on the same instance throws `IllegalStateException` with the message "Already executed." To repeat a request, for a retry button or simple polling, call `clone()`: it creates a new call with the same parameters that has not been executed yet. The RxJava 3 adapter relies on the same rule and clones the call for every subscription. ## Common mistakes - Calling `execute()` from an `Activity` or a click listener on the main thread. - Treating `onResponse` as success and reading `body()` without checking `isSuccessful`. - Posting the callback result to the main thread by hand on Android, where the default executor has already done it. - Reusing a finished `Call` for a retry instead of cloning it. - Doing heavy work inside `onResponse`, which on Android runs on the main thread like any other UI code. ## Where Call still fits Most Kotlin code now declares `suspend` methods, which enqueue under the hood and resume a coroutine instead of calling a `Callback`. A plain `Call` return type remains useful in a few places: - Java modules and libraries that cannot use coroutines. - Synchronous work on a thread you already own, such as a background job that runs one request after another. - Code that needs the `Call` object itself, for example to `clone()` it for polling or to read `request()` before sending. Cancelling an in-flight call with `cancel()` is covered in its own question; in short, on Android a cancelled enqueued call still reports through `onFailure`.
- What happens if you call enqueue() twice on the same Retrofit Call, and how do you retry correctly?The second call throws `IllegalStateException` with "Already executed.", because a `Call` is single-use whether it finished or not. Call `clone()` to get a fresh, unexecuted call with the same parameters and enqueue that one.
- How do you keep a Retrofit Callback off the main thread, for one method or for all of them?Annotate a single method with `@SkipCallbackExecutor` and its callback runs on the OkHttp thread that made the call. To change every `Call`-returning method, pass your own executor to `Retrofit.Builder.callbackExecutor()`. Neither affects return types handled by other adapters, such as RxJava types.
- When you use enqueue() on Android, is the response body converted on the main thread?No. Retrofit converts the body on OkHttp's background thread and only then posts the finished `Response` to the main thread, so a large JSON payload does not stall the UI during parsing. Request building, including body serialization by most converters, happens on whichever thread calls `enqueue()`.
- Retrofit enqueue callbacks run on a background thread on Android, so post them to the UI yourself.
- onResponse means the request succeeded, so body() is always safe to use.
- A finished Retrofit Call can be enqueued again to retry it.
- execute() is fine on the main thread for small responses.
- onFailure fires when the server returns HTTP 500.