skip to content

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%

answer

  1. a cancellable continuation around enqueue
  2. invokeOnCancellation calls Call.cancel()
  3. OkHttp call cancelled underneath
  4. blocking execute() never hears it

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.

solid answer

~40 s

Retrofit's `await()` extensions wrap `Call.enqueue()` in `suspendCancellableCoroutine` and register `invokeOnCancellation { cancel() }`, so cancelling the caller's scope cancels the Retrofit `Call`, and `OkHttpCall.cancel()` cancels the `okhttp3.Call` underneath; a call not yet started never starts. The same holds for `Call.await()` and `awaitResponse()` on an existing `Call`, and for disposing an RxJava 3 type, which cancels its cloned call. Cancellation does not reach a `call.execute()` wrapped in `withContext(Dispatchers.IO)`: the thread stays blocked until the server answers or a timeout fires, and the result is thrown away. A manually enqueued `Call` is cancelled only if you keep it and call `cancel()`, and on Android its callback then still runs `onFailure` with an `IOException`. Cancelling stops the client waiting; it cannot undo a request the server already received.

code

kotlin · 29 lines
kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.await
import retrofit2.http.GET
import retrofit2.http.Path

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

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

    @GET("orders/{id}")
    fun orderCall(@Path("id") id: Long): Call<Order>
}

class OrdersRepository(private val api: OrdersApi) {
    // Cancelling the caller's coroutine cancels the OkHttp call.
    suspend fun order(id: Long): Order = api.order(id)

    // Same guarantee for an existing Call: await() cancels it with the coroutine.
    suspend fun orderFromCall(id: Long): Order = api.orderCall(id).await()

    // Anti-pattern: cancellation never reaches this request; the IO thread
    // stays blocked until the server answers or a timeout fires.
    suspend fun orderBlocking(id: Long): Order? =
        withContext(Dispatchers.IO) { api.orderCall(id).execute().body() }
}

go deeper

for a junior

Remember that cancelling the coroutine scope of a suspend Retrofit call also cancels the HTTP request, while a plain Call needs its own cancel().

for a middle

Explain the chain: suspendCancellableCoroutine, invokeOnCancellation calling Call.cancel(), OkHttpCall cancelling the OkHttp call, and the CancellationException the caller sees.

for a senior

Spot where the chain breaks: blocking execute() in withContext, wrappers that do not forward cancel(), and enqueue callbacks reporting onFailure after a deliberate cancel.

for a principal

Set the rule that legacy Call code is bridged with await() rather than execute(), and be clear that cancellation is a client-side courtesy, never a server-side undo.

## Retrofit's cancellation path for suspend methods A **cancellation path** is the chain by which "the caller no longer wants this" travels from the code that gave up down to the socket. For a Retrofit `suspend` method that chain is built into Retrofit's own Kotlin extensions: 1. The service method is adapted as a `Call<T>` and awaited with `await()` or `awaitResponse()` from `retrofit2.KotlinExtensions`. 2. Those functions use `suspendCancellableCoroutine` and register `continuation.invokeOnCancellation { cancel() }` before calling `enqueue()`. 3. When the coroutine's job is cancelled, for example because a `viewModelScope` is cleared, the handler runs and calls `Call.cancel()` on the Retrofit call. 4. `OkHttpCall.cancel()` sets its `canceled` flag and, if the `okhttp3.Call` exists, cancels it. If the call had not been started yet, it will never be sent. 5. OkHttp aborts the exchange; an in-flight read or write ends with an `IOException`. 6. The coroutine itself has already resumed with a `CancellationException`, so the late failure is ignored. How coroutine cancellation itself propagates through a scope is covered in the lesson on Kotlin coroutines; the part specific to Retrofit is steps 2 to 5. ## What Call.cancel() does - **Before execution**: the call is marked cancelled and never sent; a later `enqueue()` cancels the new OkHttp call immediately. - **In flight**: OkHttp is told to cancel; whatever stage the exchange is in, connecting, writing or reading, ends with an `IOException`. - **After completion**: nothing to cancel; the call has already reported its result. - **Through wrappers**: Retrofit's Android `ExecutorCallbackCall` and well-written custom `Call` wrappers forward `cancel()` to their delegate; a wrapper that does not breaks the chain. ## Per return type | How the request is made | What cancels the HTTP call | What the caller observes | |---|---|---| | `suspend` service method | cancelling the coroutine | `CancellationException` | | `Call.await()` or `awaitResponse()` on an existing `Call` | cancelling the coroutine | `CancellationException` | | `Call.enqueue(callback)` | your own `call.cancel()` | on Android, `onFailure` with an `IOException` | | RxJava 3 type from the adapter | `dispose()` | nothing; the adapter suppresses the late error | | `call.execute()` inside `withContext(Dispatchers.IO)` | nothing from the coroutine | the request completes, then `CancellationException` | ## The blocking-execute trap Code written before suspend methods, or copied from Java, often looks like `withContext(Dispatchers.IO) { api.orderCall(id).execute() }`. It works, but `execute()` is a blocking call that knows nothing about the coroutine. When the scope is cancelled: - the IO thread stays blocked until the server responds or a timeout fires; - the request is sent and the response downloaded and converted, then discarded; - with many such calls, the IO dispatcher's threads are tied up by work nobody wants. The fix is to let Retrofit own the bridge: declare the method `suspend`, or call `await()` on the existing `Call`. Both cancel the `Call` with the coroutine. ## The manual enqueue case With callbacks there is no scope, so the code that starts a `Call` must keep a reference and call `cancel()` when the screen goes away. On Android the default callback executor reports a call that was cancelled before delivery through `onFailure` with an `IOException` rather than `onResponse`, so a callback that shows an error message should check `call.isCanceled` first. ## Checking it in a test - For a suspend method, start the call against a mock server that delays its response, cancel the job, and assert that the coroutine ended with `CancellationException` long before the delay ran out. - For an existing `Call` awaited with `await()`, also assert that `call.isCanceled` is true afterwards. - Run the same test against the `execute()` version: it finishes only after the full delay, which is exactly the regression such a test guards against. ## What cancellation cannot do Cancelling stops the client from waiting; it does not recall a request. If the server already received a POST, the order may be placed even though the app never sees the answer. Whether a screen should cancel a write at all is a design question for the request pipeline, covered in the mobile system design material on API requests; this question covers what Retrofit does once you do cancel.

  • A custom Retrofit Call wrapper forgets to forward cancel(). What breaks?
    Retrofit's `invokeOnCancellation` calls `cancel()` on the wrapper, which does nothing, so the OkHttp request keeps running after the coroutine is cancelled. The coroutine still resumes with `CancellationException`, which hides the bug; you see it only as wasted traffic or a request that completes on the server after the user left.
  • After calling cancel() on an enqueued Retrofit Call on Android, does the Callback still run?
    Yes. Exactly one callback method runs for every call, and for a cancelled one Retrofit's Android callback executor reports `onFailure` with an `IOException` rather than `onResponse`. Code that shows an error toast in `onFailure` should check `call.isCanceled` first, or the user sees an error for a request they abandoned.

  • Cancelling the coroutine leaves a Retrofit suspend request running to completion.
  • Wrapping execute() in withContext(Dispatchers.IO) makes it cancellable.
  • After Call.cancel() an enqueued callback on Android is never invoked.
  • Cancelling a Retrofit call undoes a POST the server already received.
  • Disposing a Retrofit RxJava 3 Single delivers an onError with an IOException.