Sub topic 4
Building pipelines with map, flatMap, and friends
This chapter assumes you know Java lambdas and generics, basic Spring Boot, and the difference between Mono (zero or one result) and Flux (zero to many results). It covers the operators you use most often and the mistakes that come with them.
A pipeline is a recipe
An operator is a method on Mono or Flux that returns a new publisher wrapping the old one. Chaining operators builds a pipeline. Nothing runs until something subscribes. In a WebFlux application, the framework subscribes for you when it writes the response.
Flux<Integer> odds = Flux.range(1, 5)
.map(n -> n * n)
.filter(n -> n % 2 == 1);
odds.subscribe(System.out::println); // prints 1, 9, 25If you delete the subscribe line, nothing prints. This is the most common first surprise.
Transforming and filtering
mapconverts each element to another element, one to one and synchronously.filterdrops elements that fail a test.switchIfEmptysupplies an alternative publisher when the source completes without emitting anything.
The controller lookup from earlier chapters uses switchIfEmpty to turn a missing book into a 404:
return repository.findById(id)
.switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)));map or flatMap
Use map when your function returns a plain value. Use flatMap when your function returns a Mono or Flux, such as a repository call, a WebClient call, or a ServerResponse. flatMap subscribes to the inner publisher and merges its results into the outer stream.
Mono<ServerResponse> get(ServerRequest request) {
return repository.findById(request.pathVariable("id"))
.flatMap(book -> ServerResponse.ok().bodyValue(book))
.switchIfEmpty(ServerResponse.notFound().build());
}Here map would give you a Mono<Mono<ServerResponse>>, which the framework cannot write as a response. When you see nested publishers in a type signature, you almost always wanted flatMap.
| Operator | Your function returns | Result type |
|---|---|---|
| `map` | A value `R` | `Mono<R>` or `Flux<R>` |
| `flatMap` | A `Mono<R>` or `Flux<R>` | `Mono<R>` or `Flux<R>` |
On a Flux, flatMap runs the inner publishers concurrently. Results can arrive in a different order than the inputs. Use concatMap when order matters. It processes one inner publisher at a time.
Flux<String> ids = Flux.just("1", "2", "3");
Flux<Book> ordered = ids.concatMap(repository::findById);Combining publishers
zipwaits for one element from each source and combines them. Use it for independent calls whose results you need together.mergeinterleaves several sources as items arrive.thenignores the result and continues once the source completes.
Mono<String> summary = Mono.zip(
repository.findById("1"),
repository.findById("2"))
.map(tuple -> tuple.getT1().title() + " & " + tuple.getT2().title());If either source of zip is empty, the result is empty too.
Common errors
- Forgetting to subscribe or return. Calling
repository.save(book)and discarding the returnedMonodoes nothing. Return it, or chain it into the pipeline. - Using
mapwhereflatMapis needed. The compiler will show a nestedMono<Mono<...>>type. - Blocking inside an operator. Calling
.block()or a slow synchronous method insidemapstalls the event-loop thread. Later chapters cover how to handle this. - Assuming
flatMapkeeps order. It does not. Switch toconcatMap.
Exercise
A handler calls repository.findById(id).map(book -> ServerResponse.ok().bodyValue(book)). What type does the pipeline produce, and which operator should replace map?
Show answer
It produces Mono<Mono<ServerResponse>>, because ServerResponse.ok().bodyValue(book) itself returns a Mono<ServerResponse>. Replace map with flatMap so the inner Mono is flattened into a Mono<ServerResponse>.
Exercise
You load ten books by id with flatMap and the output order differs from the input order. How do you fix it?
Show answer
Replace flatMap with concatMap, which subscribes to one inner publisher at a time and keeps the input order.