Spring Web Reactive | 2. WebClient | 2.3. Exchange
The exchangeToMono() and exchangeToFlux() methods, or awaitExchange { } and exchangeToFlow { } in Kotlin, are useful for advanced cases that require more control, such as decoding responses differently depending on their status.
Java
Mono<Object> entityMono = client.get()
.uri("/persons/1")
.accept(MediaType.APPLICATION_JSON)
.exchangeToMono(response -> {
if (response.statusCode().equals(HttpStatus.OK)) {
return response.bodyToMono(Person.class);
}
else if (response.statusCode().is4xxClientError()) {
// Suppress error status code
return response.bodyToMono(ErrorContainer.class);
}
else {
// Turn to error
return response.createException().flatMap(Mono::error);
}
});
Kotlin
val entity = client.get()
.uri("/persons/1")
.accept(MediaType.APPLICATION_JSON)
.awaitExchange {
if (response.statusCode() == HttpStatus.OK) {
return response.awaitBody<Person>()
}
else if (response.statusCode().is4xxClientError) {
return response.awaitBody<ErrorContainer>()
}
else {
throw response.createExceptionAndAwait()
}
}
When you use these methods, after the returned Mono or Flux completes, the response body is checked and released if it has not been consumed, preventing memory and connection leaks. The response can no longer be decoded downstream. The provided function is responsible for declaring how to decode the response when necessary.