🕐 Reading time: 2 minutes

When we work with WebFlux, improving the readability of our code is essential. Let's look at a practical example!

Let's assume we have the following methods:

List<Student> getStudents() { ... }
Mono<Student> validateStudent(final Student student) { ... }
Mono<Grade> calculateGradeForStudent(final Student student) { ... }

and that we need to rewrite this snippet of code:

Mono.just(getStudents())
    .flatMapIterable(UnaryOperator.identity())
    .flatMap(this::validateStudent)
    .flatMap(student -> Mono.zip(
            Mono.just(student),
            calculateGradeForStudent(student)))
    .map(tuple2 -> ...)

We can be more concise by using the zipWhen operator:

Flux.fromIterable(getStudents())
    .flatMap(student -> validateStudent(student)
            .zipWhen(this::calculateGradeForStudent))
    .map(tuple2 -> ...)

📌 Conclusion

The zipWhen operator lets us "combine" two operations where the second one (calculateGradeForStudent) runs only after the first (validateStudent), since it depends directly on it. This improves readability and, in our case, also guarantees that the grade is computed for each student in a controlled and sequential way.

On top of that, zipWhen gives us a Tuple2<Student, Grade> as output. This is particularly handy when you want access to both objects for further processing down the line.

🔍 Extra considerations

See you at the next pill! ☕