Sub topic 4
Building pipelines with map, flatMap, and friends
This chapter covers how to compose Mono and Flux results with operators. It assumes you know Java lambdas and generics, basic Spring Boot, and the Mono and Flux types from the previous chapter. You should also know that a Mono holds zero or one value and a Flux holds zero to many.
The working model: assembly versus subscription
An operator is a method on Mono or Flux that returns a new Mono or Flux. Chaining operators builds a pipeline. Each operator wraps the one before it and describes what to do with the signals that flow through.
Nothing runs while you build the chain. This is called assembly. Work starts only when something subscribes, and the data then flows from the source down to the subscriber.
import reactor.core.publisher.Flux;
public class OddSquares {
public static void main(String[] args) {
Flux<Integer> odds = Flux.range(1, 5)
.map(n -> n * n)
.filter(n -> n % 2 == 1);
System.out.println("Assembled, nothing printed yet");
odds.subscribe(System.out::println); // prints 1, 9, 25
}
}The first line of output appears before any number. In a WebFlux application you rarely call subscribe yourself. The framework subscribes when it writes the response, so your job is to return the pipeline.
Transforming values with map
map applies a synchronous function to each element and emits the result. Use it when the function returns a plain value and does not block.
Mono<String> name = repository.findById(id)
.map(book -> book.getTitle().toUpperCase());If the Mono is empty, the lambda never runs, and the result is still empty. That means you never need a null check inside map for the source element. It also means a map function must not return null. Reactor rejects null values with a NullPointerException, which travels down the pipeline as an error signal.
Filtering and narrowing
filter keeps elements that match a predicate. On a Mono, a failed predicate turns the result into an empty Mono. Other operators you will use often:
take(n)keeps the first n elements and then cancels the upstream source.skip(n)drops the first n elements.distinct()drops repeated elements. It keeps a set of everything it has seen, so use it with care on unbounded streams.next()turns a Flux into a Mono holding the first element.
Chaining asynchronous steps with flatMap
Use flatMap when your function returns a Mono or Flux instead of a plain value. This is the most important operator to understand. If you used map here, you would get a nested Mono<Mono<User>>, which does nothing useful.
Mono<User> owner = bookRepository.findById(bookId)
.flatMap(book -> userRepository.findById(book.getOwnerId()));On a Flux, flatMap subscribes to the inner publisher of each element and merges the results into one stream. Several inner publishers can be active at once, so the output order is not guaranteed.
Flux<Review> reviews = bookRepository.findAll()
.flatMap(book -> reviewClient.fetchReviews(book.getId()));The default concurrency of flatMap on a Flux is 256 inner subscriptions. You can lower it with a second argument, which protects a downstream service from too many parallel calls.
Flux<Review> gentle = bookRepository.findAll()
.flatMap(book -> reviewClient.fetchReviews(book.getId()), 4);Choosing between flatMap, concatMap, and flatMapSequential
| Operator | Inner publishers run | Output order | Use when |
|---|---|---|---|
| `flatMap` | In parallel | Order of arrival | Order does not matter and you want speed |
| `concatMap` | One at a time | Source order | Order matters, or each step depends on the last |
| `flatMapSequential` | In parallel | Source order | You want parallel work but ordered output |
flatMapSequential buffers results that finish early until earlier ones are done. That costs memory but keeps the speed.
Combining independent results
Sometimes two calls do not depend on each other. Running them one after another with flatMap wastes time. Mono.zip subscribes to both at once and combines the results when both have produced a value.
Mono<BookDetails> details = Mono.zip(
bookRepository.findById(id),
reviewClient.averageRating(id))
.map(tuple -> new BookDetails(tuple.getT1(), tuple.getT2()));If either source is empty, zip completes empty. If either one errors, the whole result errors. Other combining operators:
Flux.mergeinterleaves several Fluxes as items arrive.Flux.concatemits all of the first Flux, then all of the second.Mono.then()waits for completion and discards the value, which suits "save, then continue" steps.thenReturn(value)waits for completion and then emits a fixed value.
Handling empty results
An empty Mono is not an error. It is a normal result that means "no value". Two operators cover most cases.
Mono<Book> orDefault = repository.findById(id)
.defaultIfEmpty(Book.placeholder());
Mono<Book> orFail = repository.findById(id)
.switchIfEmpty(Mono.error(
new ResponseStatusException(HttpStatus.NOT_FOUND)));defaultIfEmpty supplies a single value. switchIfEmpty switches to another publisher, which lets you run a fallback lookup or raise an error.
Collecting and reducing a Flux
Some operators gather many elements into one result and return a Mono.
Mono<List<String>> titles = repository.findAll()
.map(Book::getTitle)
.collectList();
Mono<Integer> totalPages = repository.findAll()
.map(Book::getPages)
.reduce(0, Integer::sum);
Mono<Long> howMany = repository.findAll().count();These operators wait for the Flux to complete, so they hold everything in memory and never finish on an endless stream. Prefer returning the Flux itself from a controller when you can. Use collectList only when you need the whole list at once.
Looking inside a pipeline
doOnNext, doOnError, and doOnComplete run a side effect without changing the data. They suit logging and metrics. The log() operator prints every signal that passes through, which helps when you are learning.
Flux<Integer> traced = Flux.range(1, 3)
.doOnNext(n -> System.out.println("saw " + n))
.map(n -> n * 10)
.log();Common errors
- Forgetting to subscribe. A pipeline that is neither returned nor subscribed does nothing. A call such as
repository.save(book);on its own line saves nothing. - Using map where flatMap is needed. The compiler accepts
Mono<Mono<T>>, and the inner Mono is never subscribed. Check your types when a step does not seem to run. - Blocking inside an operator. Calling
block()or a blocking client in amaplambda stalls the thread that runs the pipeline. Later chapters cover this in detail. - Assuming flatMap keeps order. Results arrive in completion order. Switch to
concatMaporflatMapSequentialif order matters. - Mutating shared state in lambdas. Elements can be handled on different threads. Keep lambdas free of shared mutable variables.
- Eager arguments. Arguments such as the one in
switchIfEmptyare evaluated while you build the chain. Usedeferfor work that must be lazy.
Exercise
A controller method must return the owner of a book, given a book ID. bookRepository.findById(id) returns Mono<Book>, and userRepository.findById(ownerId) returns Mono<User>. Which operator connects the two calls, and what happens if you use map instead?
Show answer
Use flatMap, because the second step returns a Mono. With map you get a Mono<Mono<User>>. The inner Mono is never subscribed, so the user lookup never runs and the client receives no useful body.
Exercise
You have a Flux<Book> and call flatMap(book -> reviewClient.fetchReviews(book.getId())). The reviews come back in a different order than the books. Why does this happen, and which operator keeps the books' order while still running the calls in parallel?
Show answer
flatMap subscribes to the inner publishers at the same time and emits results in the order they finish, so a fast call can overtake a slow one. flatMapSequential runs the calls in parallel but emits results in source order. concatMap also keeps order, but it runs one call at a time.