Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my method return a value computed within a lambda expression?

Here's a simplified version of what my code looks like:

public void pairing() {
    WebClient web = WebClient.create(vertx);
    String url = "/request";
    JsonObject obj = new JsonObject();
    web
        .post(6660, "localhost", url)
        .sendJsonObject(obj, response -> {
            JsonObject pairing = response.result().body().toJsonObject(); // what I want to return
        }
}

This makes a POST request to localhost:6660/request, and I create a new JsonObject called pairing that stores the response to that request. I could process pairing inside of the lambda expression for the request, but ideally, I would be able to return the JsonObject to the method that calls pairing() and process it from there.

I tried this:

public JsonObject pairing() {
    JsonObject pairing = new JsonObject();
    WebClient web = WebClient.create(vertx);
    String url = "/request";
    JsonObject obj = new JsonObject();
    web
        .post(6660, "localhost", url)
        .sendJsonObject(obj, response -> {
            pairing = response.result().body().toJsonObject();
        }
    return pairing;
}

But it doesn't work because I get the "pairing must be final or effectively final" error. Is there some way I can return "pairing" from this method so that I can access it elsewhere in my program? Or am I possibly approaching this the wrong way?

like image 289
Imran Avatar asked Aug 02 '17 18:08

Imran


1 Answers

Use futures:

public Future<JsonObject> pairing() {
        Future<JsonObject> future = Future.future();
    WebClient web = WebClient.create(vertx);
    String url = "/request";
    JsonObject obj = new JsonObject();
    web
        .post(6660, "localhost", url)
        .sendJsonObject(obj, response -> {
            future.complete(response.result().body().toJsonObject());
        }
    return future;
}

Now to call this function:

pairing().setHandler(r -> {
    r.result // This is your JSON object
});

WebClient will execute asynchronously. What you are trying is synchronous, which is not possible using WebClient, and also synchronous call will be a blocking call in vert.x. Thats also the golden rule, do not block the event loop.

like image 134
Niraj Chauhan Avatar answered Oct 13 '22 23:10

Niraj Chauhan