Back from holiday, I'm ready to kick off my personal Java Pills rubric! 🎉 To warm up the engines, let's start with something light but definitely useful about reactive programming.

🔍 Why use doOnNext?

WebFlux's doOnNext method is used to run secondary actions for every element emitted by a publisher, such as a Flux or a Mono, without altering the data-flow. It is often used for logging, metadata updates, side-effects or other actions that need to run for each emitted element.

Example: imagine you have to update a car's license plate.

Original code (not optimal):

Mono.just(licensePlate)
    .map(plate -> {
        sampleCar.setLicensePlate(plate);
        return plate;
    })
    .map(plate -> ...);

Improved code using the doOnNext construct:

Mono.just(licensePlate)
    .doOnNext(sampleCar::setLicensePlate)
    .map(plate -> ...);

Using doOnNext in this context improves the readability and maintainability of the code, making it clearer that sampleCar.setLicensePlate is a consequence of the value being emitted and not a transformation of the value itself!