Hegdekar
Hegdekar

Reputation: 1167

How to achieve composing of Vert.x AsyncResult<T>?

While performing a operation which might fail or succeed I have been using the Handler<AsyncResult<T>> so that result can be asynchronously passed when ready.

For example operation may be something like adding an entry into cache, like below

public void putEnvironmentVariable(String variableName, EnvVariable variable, Handler<AsyncResult<Long>> rsHandler) {
    redisClient.hset(ENV_CACHE, variableName, Json.encode(variable), rsHandler);
  }

In the above example I'm making use of Vert.x-redis add entry into a set.

Now if the same has to be done to add multiple entries into cache, I'm doing it like mentioned below

list.forEach(envVariable -> {
        redisUtils.putEnvironmentVariable(envVariable.getName(), envVariable, result -> {

        });
      });

Questions:

1) Is this approach right ? or can it be done in a simpler/better way?

2) Here I've taken an example, but in general if there is a need to perform some operation like mentioned above and result of all operations combined to be passed on to the calling method how can that be achieved in vert.x?

I'm using Vert.x 3.6.3

Upvotes: 0

Views: 276

Answers (1)

Francesco Guardiani
Francesco Guardiani

Reputation: 688

When you have to perform several async operations and combine the result of them into one result, you have two choices:

Using Vert.x Future

You wrap the redisClient.hset() async result in a Vert.x Future and then join all that async operations using Vert.x CompositeFuture:

Future<Long> fut = Future.future();
redisClient.hset(ENV_CACHE, variableName, Json.encode(variable), fut);

Then when you have a list of all futures you can use CompositeFuture:

CompositeFuture
  .all(futuresList)
  .map(cf -> /*aggregate all results in one single result*/)

Using Vert.x with RxJava 2

If you are using Vert.x with RxJava 2, you can merge all Single using combinators and then compose the final result with aggregators


The choice depends on you, anyway I suggest you give a look at Vert.x with RxJava 2. The RxJava 2 operators play well with Vert.x async operations and allow you to easily solve problems like these

Upvotes: 1

Related Questions