Home > Net >  How do I add a delay with data from the Mono?
How do I add a delay with data from the Mono?

Time:04-26

I have a service that is returning a value which contains delay information.

  public Mono<R> authenticate(
      A authenticationRequest,
      @RequestHeader Map<String, String> headers,
      ServerHttpResponse serverHttpResponse) {

    final AuthServiceResponse<R> authenticationResponse = authService.authenticate(authenticationRequest, headers);
    serverHttpResponse.setStatusCode(authenticationResponse.getStatusCode());
    return Mono.just(authenticationResponse.getOperationResponse())
        .delayElement(authenticationResponse.getDelay());
  }

I'd like to try to convert it so it is reactive I got this far...

  public Mono<R> authenticate(
      A authenticationRequest,
      @RequestHeader Map<String, String> headers,
      ServerHttpResponse serverHttpResponse) {

    return authService.authenticate(authenticationRequest, headers)
            .map(authenticationResponse->{
              serverHttpResponse.setStatusCode(authenticationResponse.getStatusCode());          
              return authenticationResponse.getOperationResponse()
            });
      ...

but I wasn't sure how to add the "delayElement" capability.

CodePudding user response:

Try this to add delay based on your authenticationResponse.getDelay() value

public Mono<Object> authenticate(Object authenticationRequest,@RequestHeader Object headers,
        Object serverHttpResponse) {

    return authenticate(authenticationRequest,headers)
            .flatMap(authenticationResponse -> {
                Mono<String> delayElement = Mono.just("add delay")
                        .delayElement(Duration.ofSeconds(authenticationResponse.getDelay()));
                Mono<Object> actualResponse =Mono.just(authenticationResponse.getOperationResponse());
                return Mono.zip(delayElement,actualResponse).map(tupleT2 -> tupleT2.getT2());
            });

}

let me know if it doesn't work. i will try to find other way.

CodePudding user response:

You can use Mono.fromCallable delayElement within a flatMap like this:

return authService.authenticate(authenticationRequest, headers)
         .flatMap(authenticationResponse -> {
           return Mono.fromCallable(() -> authenticationResponse.getOperationResponse())
                      .delayElement(authenticationResponse.getDelay())
            });
  • Related