S3 streaming responses are scoped to a lambda block to simplify lifetime management. Instead of the API returning the response object directly, you must provide a lambda that receives the response.
Critical Rule: The response and its underlying stream are only valid within the scope of the provided lambda. Do not attempt to store the response object or process the stream after the block returns.
To use this pattern, pass a lambda to methods like getObject and perform your stream processing (e.g., writing to a file) inside that block.
val s3 = S3Client { ... }
val req = GetObjectRequest { ... }
val path = Paths.get("/tmp/download.txt")
val contentSize = s3.getObject(req) { resp ->
// resp is valid only until the end of this block
val rc = resp.body?.writeToFile(path)
rc
}
println("wrote $contentSize bytes to $path")