pixel
pixel

Reputation: 26441

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.

Upvotes: 0

Views: 733

Answers (1)

pixel
pixel

Reputation: 26441

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

Upvotes: 3

Related Questions