Brijesh Prasad
Brijesh Prasad

Reputation: 579

Java Loop until condition for webclient returning Mono

I have a java webclient code , the response of which I convert to Mono. I want to iterate on the api call until the Mono response matches certain condition. Of course I do not want to iterate till infinity. I want to iterate after every 5 seconds until 30 seconds. So far I have tried this

client.get()
                .uri("https://someUri")
                .retrieve()

                .bodyToMono(Response.class)
                .delayElement(Duration.ofSeconds(5))
                .retryBackoff(5, Duration.ofSeconds(5))
                .delayUntil(r -> {
                    System.out.print("Looping"); 
                    if(condition) {
                        System.out.print(r.getStatus());
                        return Mono.just(r);
                    }
                    return Mono.empty();
                })

But no use.

Upvotes: 1

Views: 4201

Answers (1)

123
123

Reputation: 11216

You can use a filter, repeatWhenEmpty and Repeat like so

client.get()
    .uri("https://someUri")
    .retrieve()
    .bodyToMono(Response.class)
    .filter(response -> condition)
    .repeatWhenEmpty(Repeat.onlyIf(r -> true)
        .fixedBackoff(Duration.ofSeconds(5))
        .timeout(Duration.ofSeconds(30)))

The Repeat class is part of the reactor-extra library

<dependency>
    <groupId>io.projectreactor.addons</groupId>
    <artifactId>reactor-extra</artifactId>
</dependency>

Upvotes: 4

Related Questions