1
vertx.setPeriodic(1000, id -> {
    //api call
    if (count == 4){
        vertx.cancelTime(id); 
    }
});

Now the problem is I don't want a fix 1000 ms time, I just want to call the api 4 times and then go with final api response for further processing , please help.

Vishal Rathore
  • 137
  • 1
  • 13

1 Answers1

2

One way is to use a recursive approach.

Therefore you can implement something like this as an convenient entrypoint

private Future<YourResultType> callApiNTimes(final int repetitions) {
    final Promise<YourResultType> p = Promise.promise();

    recursiveApiCalls(p, 0, repetitions);

    return p.future();
}

Recursion implemented as following

private void recursiveApiCalls(final Promise<YourResultType> p, final int counter, final int maxRepetitions) {
    yourRawApiCall().onComplete(reply -> {
        if (reply.failed()) {
            p.fail(reply.cause());
            return;
        }

        if (counter < maxRepetitions) {
            recursiveApiCalls(p, counter + 1, maxRepetitions);
            return;
        }

        p.complete(reply.result());
    });
}

At the end implement yourRawApiCall and then use it like this

callApiNTimes(4).onComplete(reply -> {
    if (reply.failed()) {
        // Something went wrong, do your error handling..
        return;
    }

    final YourResultType result = reply.result();

    // Do something with your result..
});

Antoher approach would be to put your API calls as Futures in a list and execute this list in parallel with CompositeFuture.all, CompositeFuture.join, .. instead of one after another.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Philipp
  • 383
  • 4
  • 11