2

I am trying to understand why a flatmap() is used on the response stream, in this post, for example (copy pasted directly from the reference)

final ClientRequest request = ClientRequest.GET(url)
        .accept(MediaType.TEXT_EVENT_STREAM).build();
Flux<Alert> alerts = webClient.exchange(request)
        .flatMap(response -> response.bodyToFlux(Alert.class));

AFAIK, a flatmap applied on a stream produces an arbitrary number of values (0...n) for each input value (in the stream). So a flatmap takes a function that produces a stream.

A flux emits 0 or more items, and then optionally either completing or erroring.

So what exactly is happening on the response stream? Is this the function that takes the response stream, and emits 0 or more objects of the class Alert? So if we subscribe to alerts, we can get them over the web client in a reactive manner. Can someone clarify if I am correct, please?

code4kix
  • 3,937
  • 5
  • 29
  • 44

1 Answers1

3

Yes that is correct. The receiving of the header is a first async stage, at which point you get a response. You then use flatMap to asynchronously retrieve the body. Said body is a Flux, because in some cases you can get multiple unmarshalled objects (eg SSE). Here you'd probably get only one Alert.

Simon Baslé
  • 27,105
  • 5
  • 69
  • 70
  • It seems the flatMap is not required anymore given that the WebClient.ResponseSpec offers the bodyToFlux method. This is crystal clear to me. However, I still haven't understood why the flatMap was required in the first place. If we were expecting a stream of alerts, a perfect match to flux, why would flatMap be required? I cannot see the "stream of streams" here. Could you please help me out? – dbaltor Mar 20 '20 at 13:10
  • I think you are right, hence the correction on the original post. stream of streams ... is not what it should have been. Things have improved quite a bit now. This is just an outdated example I think. – code4kix Mar 25 '20 at 02:40