skip to content

In Retrofit, what does @Streaming change when a service method downloads a large PDF as a ResponseBody, and what must the caller then do?

level: middleimportance: should knowfreq 33%

answer

  1. the default copies everything first
  2. a live body instead of a buffer
  3. read it off the main thread
  4. close it when done

basics

~20 s

Without @Streaming, Retrofit reads a ResponseBody fully into memory before returning it; with @Streaming it returns the live network body. The caller must then read it off the main thread, copy it to a file in chunks, and close it.

solid answer

~40 s

For a `ResponseBody` return type, Retrofit's built-in converter normally copies the whole body into an in-memory Okio buffer and closes the network stream, so a 300 MB PDF means a 300 MB allocation and often an `OutOfMemoryError`. `@Streaming` on the method makes Retrofit return the body as is: a `suspend` method resumes once the headers arrive, and the bytes come off the connection as you read `source()`. The caller then owns three things: reading on a background dispatcher, because reading now does network I/O; copying in chunks to a file sink with `writeAll` rather than calling `bytes()` or `string()`; and closing the body with `use {}`, or OkHttp eventually logs a leaked connection. `@Streaming` does not change error bodies, which Retrofit always buffers, and an `HttpLoggingInterceptor` at `Level.BODY` buffers the whole download anyway.

code

kotlin · 23 lines
kotlin
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import okio.buffer
import okio.sink
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Streaming

interface ReportsApi {
    @Streaming
    @GET("reports/{id}/pdf")
    suspend fun downloadPdf(@Path("id") id: String): ResponseBody
}

suspend fun savePdf(api: ReportsApi, id: String, target: File) {
    withContext(Dispatchers.IO) {
        api.downloadPdf(id).use { body ->
            target.sink().buffer().use { out -> out.writeAll(body.source()) }
        }
    }
}

go deeper

for a junior

Recall that Retrofit buffers a ResponseBody in memory by default, and that @Streaming hands back the live body, which the caller must read and close.

for a middle

Explain the built-in converter's choice between buffering and streaming, why the suspend call returns at the headers, and why reading belongs on Dispatchers.IO with use {}.

for a senior

Diagnose an out-of-memory download: a missing @Streaming, a bytes() call, or a body-level logging interceptor; and spot leaked connections from unclosed streamed bodies.

for a principal

Set a team rule that large downloads use @Streaming on a client without body logging, so a debug convenience never decides whether a release build can fetch a big file.

## The default: Retrofit buffers a ResponseBody When a service method's return type is OkHttp's `ResponseBody` (directly, or inside `Response<ResponseBody>` or `Call<ResponseBody>`), no JSON converter is involved: Retrofit's **built-in converters** handle it, and they are always consulted before any factory you register. Without further instructions, the built-in converter **buffers** the body: it reads every byte into an in-memory Okio `Buffer`, closes the network stream and returns a `ResponseBody` backed by that buffer. That default is deliberate. A buffered body can be read later on any thread without touching the network, and the connection is released at once. For a small JSON or text body it is the right choice. For a large file it is the classic mistake: a 300 MB PDF becomes a 300 MB allocation in the app's heap before your code sees the first byte, which on many Android devices ends in an `OutOfMemoryError`. ## What @Streaming changes `@Streaming` is a method annotation that tells the built-in converter to skip the copy and return the network body as is: ```kotlin @Streaming @GET("reports/{id}/pdf") suspend fun downloadPdf(@Path("id") id: String): ResponseBody ``` - A `suspend` method now returns as soon as the response **headers** arrive; the body is still on the connection. - Every read from `source()` or `byteStream()` pulls more bytes from the network. - The annotation only affects a `ResponseBody` return; a method returning a model class is converted, and therefore fully read, either way. - With `Call<ResponseBody>` and `enqueue`, Retrofit delivers `onResponse` on the main thread on Android, so the callback holds a live body it must not read there: hand the copy to a background thread and close the body when it finishes. - `Call.execute()` returns the streamed body on the calling thread, which must already be a background thread. ## Reading and saving the body The caller now owns work the buffering converter used to do: 1. **Pick the thread.** Reading performs network I/O, so it belongs on `Dispatchers.IO`; on the main thread Android throws `NetworkOnMainThreadException`. 2. **Copy in chunks.** `target.sink().buffer().use { it.writeAll(body.source()) }` streams segment by segment with flat memory. Calling `bytes()` or `string()` pulls the whole file into memory again and undoes the annotation. 3. **Read once.** A streamed body is a one-shot stream; a second read finds it exhausted. 4. **Report progress if you need it** by counting bytes read against `contentLength()`, which is `-1` when the server sends no length. ## Closing is the caller's job A streamed body holds a live connection, or an open cache file for a cached response. OkHttp's documentation is explicit that the response body must be closed, and failing to do so leaks resources. Wrapping the body in `use {}` closes it on success, on an exception and on coroutine cancellation alike. If a body is dropped unclosed, OkHttp's connection pool eventually reports "A connection to ... was leaked. Did you forget to close a response body?" ## What @Streaming does not change | situation | is the body held in memory? | |---|---| | a 2xx response, `@Streaming`, `ResponseBody` return | no, it streams as you read | | a 2xx response, no `@Streaming`, `ResponseBody` return | yes, fully buffered before the method returns | | a non-2xx response, with or without `@Streaming` | yes, Retrofit always buffers error bodies; a `suspend` method throws `HttpException` | | `HttpLoggingInterceptor` at `Level.BODY` on the client | yes, the interceptor buffers the whole body to log it | | `HttpLoggingInterceptor` at `Level.HEADERS` | no, headers only | Two neighbouring features are easy to confuse with it: - The `withStreaming()` factory method that Retrofit 2.12.0 added to the Gson, Jackson, Moshi, Protobuf and Wire converters is about **requests**: it defers serialising a request body until OkHttp writes it. It does nothing for downloads. - Keeping a long download alive after the screen or the process goes away is a scheduling problem for background work, not something an annotation on the service method can provide. ## A compact mental model Think of the response as water arriving through a pipe. The default fills a bucket with all of it and hands you the bucket; `@Streaming` hands you the end of the hose, which is better for a lot of water, but you must hold it somewhere other than the main thread and turn it off when you are done.

  • Does @Streaming help when the PDF request fails with a 404 or 500?
    No. Retrofit buffers every non-2xx body in memory before handing it over, whatever the annotation, so it can be read later as an error body; a `suspend` method throws `HttpException` carrying it. Error bodies are normally small, so this is rarely a problem, but a server that returns a large error page still costs that memory.
  • Why would a @Streaming download still run out of memory in a debug build?
    An `HttpLoggingInterceptor` at `Level.BODY` reads the entire response into its buffer so it can print it, before Retrofit's streaming body ever reaches your code. Use `Level.HEADERS` for clients that download large files, or keep body logging out of the client used for downloads.

Without @Streaming, Retrofit fills a bucket with the whole delivery before handing it over; with it you get the end of the hose, which suits a large delivery, but you must point it at a file and turn it off yourself.

  • @Streaming makes Retrofit save the download to a file for you.
  • A ResponseBody return type is never buffered, so @Streaming is optional.
  • Calling bytes() on the streamed body is fine for a large file.
  • The streamed body closes itself once the suspend function returns.
  • The converter's withStreaming() option streams large response downloads.
  • @Streaming also keeps error bodies of failed calls out of memory.