简体   繁体   中英

How to get the result out of EventBus using Vert.x

guys!

While using Vert.x, I found I cannot get the result out of EventBus while communicating with other Verticle.

class Result<T> {
    public T value;
    public String message;
    // ...
}

private Result<Integer> someMethod() {
        try {
            var json = new JsonObject();
            vertx.eventBus().<JsonObject>send(Service.EVENT_BUS_ADDRESS, json, ar -> {
                if (ar.succeeded()) {
                    var result = new Result<List>(ar.result().body());
                    if (result.isSuccessful()) {
                        Result.succeed(result);
                    } else {
                        Result.fail(result.message);
                    }
                } else {
                    Result.fail("Remote server error");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
        return // how can I return the result in EventBus???
    }

So how can I get the value out of the Async block and return it?

You shouldn't return the result but notify a handler instead

The following code assumes your Result.succeeed or Result.fail method return an instance of Result

private void someMethod(Handler<Result> resultHandler) {
  ...
  vertx.eventBus().<JsonObject>send(Service.EVENT_BUS_ADDRESS, json, ar -> {
            if (ar.succeeded()) {
                var result = new Result<List>(ar.result().body());
                if (result.isSuccessful()) {
                    resultHandler.handle(Result.succeed(result));
                } else {
                    resultHandler.handle(Result.fail(result.message));
                }
            } else {
                resultHandler.handle(Result.fail("Remote server error"));
            }
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM