How Vert.x deal with cycle by cycle?

Viewed 28

This is shown in the following code:

public Future<Boolean> sendHeartbeat(List<BrokerMeta> brokerMetas) {

    PromiseInternal<Boolean> resultPromise = ContextInternal.current().promise();
    for (BrokerMeta brokerMeta : brokerMetas) {
        if (null == brokerMeta.getAdr()) {
            continue;
        }
        remote(brokerMeta.getAdr());
    }

    return resultPromise.future();
}

private Future<String> remote(String addr) {
    PromiseInternal<String> promise = ContextInternal.current().promise();
    // Request remote....
    promise.complete("From remote");
    return promise.future();
}

I want the Remote methods to execute one by one and return, and then I'm pushing resultPromise down,How do I write this code?

1 Answers

You need to call .compose on the future sent from the remote(string addr) function to make sure they run one after the other i.e. the last future returned from the remote function will call compose on it and assign it to a new future which in the next iteration would call compose on it and so on

Ref: Sequential composition for arbitrary number of calls in Vertx with Futures

Stuff like this is a lot easier when you use kotlin with coroutines - because then each call can just suspend before moving on to the next iteration - so would highly recommend looking into kotlin if you are using vert.x

Related