clay
clay

Reputation: 20390

vert.x chaining async logic?

Is there a more sane way to program the following super simple set/get/close test program? Note that I had to duplicate the Redis close code and include it in both the set error path and in the get complete path.

import io.vertx.core.Vertx;
import io.vertx.redis.RedisClient;
import io.vertx.redis.RedisOptions;

public class RedisTest {
    public static void main(String[] args) throws Exception {
        Vertx vertx = Vertx.vertx();

        String host = "localhost";

        final RedisClient client = RedisClient.create(vertx,
                new RedisOptions().setHost(host));

        client.set("key", "value", r -> {
            if (r.succeeded()) {
                System.out.println("key stored");

                client.get("key", s -> {
                    if (s.succeeded()) {
                        System.out.println("Retrieved value: " + s.result());
                    } else {
                        System.out.println("Connection or Operation Failed " + s.cause());
                    }

                    System.out.println("Closing Redis connection");
                    client.close(t -> {
                        if (s.succeeded()) {
                            System.out.println("Redis closed successfully.");
                        } else {
                            System.out.println("Connection or Operation Failed " + t.cause());
                        }

                        System.out.println("Closing vertx");
                        vertx.close();
                    });
                });
            } else {
                System.out.println("Connection or Operation Failed " + r.cause());

                System.out.println("Closing Redis connection");
                client.close(s -> {
                    if (s.succeeded()) {
                        System.out.println("Redis closed successfully.");
                    } else {
                        System.out.println("Connection or Operation Failed " + s.cause());
                    }

                    System.out.println("Closing vertx");
                    vertx.close();
                });
            }
        });

        System.out.println("Exiting main");
    }
}

Upvotes: 0

Views: 279

Answers (1)

zella
zella

Reputation: 4685

I recommend see reactive api io.vertx.rxjava.redis.RedisClient. It's excellent(its main purposes) for the chained computation.

For example(I'm not tested this code):

    client.rxSet("key", "value")
      .flatMap(r -> client.rxGet("key"))
      //calls on error or success
      .doAfterTerminate(() -> {
          client.rxClose();
          vertx.close();
      }) 
      .subscribe(
        success -> System.out.println("Chain completed"),
        //all errors will be there
        error -> System.out.println(error.getMessage())
      );

Upvotes: 1

Related Questions