How can my method return the value computed in the lambda expression?

Here is 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 for localhost: 6660 / request, and I create a new JsonObject called a pairing that saves the response to this request. I could handle the pairing inside the lambda expression for the request, but ideally I could return JsonObject to a method that calls the 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 this does not work, because I get the error "mating should be final or effectively final." Is there any way to return pairing from this method so that I can access it elsewhere in my program? Or may I have approached this wrong?

+5
source share
1 answer

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 to do is synchronous, which is not possible with WebClient, and the synchronous call will be a blocking call in vert.x. The same golden rule does not block the cycle of events.

+6
source

Source: https://habr.com/ru/post/1270503/


All Articles