user3470629
user3470629

Reputation: 531

Retry the WebClient based on the response

I created a Spring webflux webclient.I want to repeat the same operation based on my response. For ex: if the data is still empty, I want to retry to get the data. How to do that ?

Flux<Data> data = webClient.get()
                .uri("/api/users?page=" + page)
                .retrieve()
                .flatMap(o -> {
                  o.subscribe(data -> {
                      if(data == null) {
                         // WHAT TO DO HERE, TO REPEAT THE SAME CALL ?
                         o.retry();
                      }
                });
                return o;
            })
            .bodyToFlux(Data.class);

Upvotes: 1

Views: 2375

Answers (1)

Pratik Sherke
Pratik Sherke

Reputation: 131

You can use retry(Predicate<? super Throwable> retryMatcher), which will retry the operation based on the throwable condition.

In below code, I am returning Mono.error if the data received from the client is null, and then based on the error condition in the retry the above operation will be executed again.

You may also limit the number of retries with,

retry(long numRetries, Predicate<? super Throwable> retryMatcher)

final Flux<Data> flux = WebClient.create().get().uri("uri").exchange().flatMap(data -> {
      if (data == null)
        return Mono.error(new RuntimeException());
      return Mono.just(data);

    }).retry(throwable -> throwable instanceof RuntimeException)
        .flatMap(response -> response.bodyToMono(Data.class)).flux();

Upvotes: 6

Related Questions