'doOnFirst element in Reactor Flux?

I would like to perform some action (side effect) only on the first emission of the element in the Flux.

Is there a way to do that?

Some context: I want to call .elapsed() on Flux and log only the first elapsed time.



Solution 1:[1]

It turns out I can perform conditional logic using .switchOnFirst operator.

So I have:

    flux
        .elapsed()
        .switchOnFirst { signal, flux ->
            if (signal.hasValue()) {
                meterRegistry.timer("my.latency", tags).record(signal.get()!!.t1, TimeUnit.MILLISECONDS)
            }

            flux // returns the whole flux
        }
        .flatMap { Mono.just(it.t2) } // back to original flux

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pixel