1. What can a handler method do by returning a ResponseBodyEmitter?
Why: A ResponseBodyEmitter is used for HTTP streaming. It lets the handler send many objects to the client over time as part of one response.
2. How is each object sent through a ResponseBodyEmitter written to the HTTP response?
Why: Each object passed to send() is converted and written to the response body by a suitable HttpMessageConverter.
3. A client calls this handler. What body does it receive?
@GetMapping("/test")
public ResponseBodyEmitter handle() {
ResponseBodyEmitter emitter =
new ResponseBodyEmitter();
Executors.newSingleThreadExecutor()
.execute(() -> {
try {
for (int i = 1; i <= 3; i++) {
emitter.send(i + "-",
MediaType.TEXT_PLAIN);
}
emitter.complete();
} catch (Exception e) {
emitter.completeWithError(e);
}
});
return emitter;
}
Why: Each call to send() writes its text to the same response. The three parts are written one after another, so the client gets 1-2-3-.
4. Why should we call complete() on the emitter after the last send()?
Why: Calling complete() marks the end of the stream. Spring then finishes the response, and the client knows no more data will come.
5. An error happens while data is being sent. Which call finishes the response because of that error?
Why:completeWithError(Throwable) ends the stream and reports the failure. The other methods do not exist on ResponseBodyEmitter.
6. Data is usually sent to the emitter from a separate thread. Why?
Why: The handler must return the emitter quickly so Spring can start the response. Another thread keeps sending objects to the client while the stream is open.
7. Why would a handler return ResponseEntity<ResponseBodyEmitter> instead of a plain ResponseBodyEmitter?
Why: Wrapping the emitter in a ResponseEntity lets us set the response status and headers. A plain emitter is also valid, but it uses default values.
8. Which statement returns the emitter with the HTTP status 202 (Accepted)?
@GetMapping("/data")
public ResponseEntity<ResponseBodyEmitter>
handle() {
ResponseBodyEmitter emitter =
new ResponseBodyEmitter();
return ...;
}
Why: The emitter is passed as the body and the status as the second argument. The other options send text only, send no body, or use a constructor that does not exist.
9. What does the second argument specify in this call?
emitter.send("Hello", MediaType.TEXT_PLAIN);
Why: The media type tells Spring how to write the object, so it can pick a matching HttpMessageConverter for it.
10. When does a client see the objects sent by a ResponseBodyEmitter?
Why: In HTTP streaming, data is written to the response as it is sent. The client can read the parts in real time while the stream is still open.