Search code examples
javareactive-programmingproject-reactor

Call a method with exponential back off until the list is not empty


I am trying to call a method until list.size !=0 in a exponential fashion. How to achieve it? I tried with the below but no luck.

   public static void main(String[] args) throws InterruptedException {

        Mono.defer(() -> myExecution())
            .repeatWhenEmpty(Repeat.onlyIf(repeatContext -> true)
                .exponentialBackoff(Duration.ofSeconds(1), Duration.ofSeconds(30))
                .timeout(Duration.ofSeconds(30))).subscribe();
    }


  private static <T> Mono<List<String>> myExecution() {
    Date date = new Date();
    List<String> data = new ArrayList();
    if(data.size() !=0) {
        return Mono.just(data);
    }
    System.out.println("Hello = " + new Timestamp(date.getTime()));
    return Mono.empty();
}

Solution

  • This worked

    public static void main(String[] args) throws InterruptedException {
    
            Mono.defer(() -> myExecution())
                .repeatWhenEmpty(Repeat.onlyIf(repeatContext -> true)
                    .exponentialBackoff(Duration.ofMillis(1000), Duration.ofSeconds(60))
                    .timeout(Duration.ofSeconds(60))).block();
        }
    
        private static <T> Mono<List<String>> myExecution() {
            Date date = new Date();
            List<String> data = new ArrayList();
            if (data.size() != 0) {
                return Mono.just(data);
            }
            System.out.println("Hello = " + new Timestamp(date.getTime()));
            return Mono.empty();
        }