Home > database >  Delay all next elements in Webflux after first one is emitted
Delay all next elements in Webflux after first one is emitted

Time:09-10

I have in my app a reactive endpoint that returns a flux from database that never ends unless communication from the front stops. What I want to accomplish is to load first element as soon as possible and then throttle next elements by adding some delay. What I accomplished so far is to delay all elements that first one is loaded after same delay as every next one.


    var connection = Mono.fromFuture(
                    () -> dataCollector.getDataFromCassandra((CassandraExposureRetrieveRequest) command.getBody()))
            .delayElement(Duration.ofMillis(delayExposure))
            .repeat()
            .share();

Does anyone know if there is a rather simple way to delay second, third etc. element from the flux ?

Kind regards, Bartek

CodePudding user response:

Since your elements come from a Mono that is repeated multiple times, you can achieve this my prepending your Flux with a single non-delayed database call Mono:

var singleCall = Mono.fromFuture(
        () -> dataCollector.getDataFromCassandra((CassandraExposureRetrieveRequest) command.getBody()));
var connection = singleCall
        .concatWith(singleCall.delayElement(Duration.ofMillis(delayExposure))
                .repeat())
        .share();
  • Related