2

I am using vert.x 2.1.5 version. And I was trying to use event looping in my project. sample code given below

JsonObject result = null;
//loop starting
for (int i=0;i<length;i++)
{

 final JsonObject jsonObject1 = jsonObject.getArray("result").get(i);                                                           
 int x = jsonObject1.getInteger("X");
 String Data = "X="+x+"&Y="+y;  
 //calling another event 
vertx.eventBus().send("event1", Data,new Handler<Message<String>() {public void   handle(Message<String>response) 
{
JsonObject jsonObject = new JsonObject(response.body());
result_arry.addArray(jsonObject.getArray("details"));
                                            }
});
} // loop end
result = resultJson("Ok",result_arry ); 
//it will create one json object with proper format 
message.reply(result.toString());

In this code my event bus is returning value before executing event loop. I need to populate my output as per event loop output How can I achieve that

NIKHIL K A
  • 328
  • 5
  • 16

1 Answers1

0

Basically, the problem is that you're not waiting for messages to arrive. For my example to be more clear I removed most of the Json logic.

Vertx vertx = Vertx.vertx();
int messages = 10;

// First register your consumer
MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer("event1");
consumer.handler(o -> {
    System.out.println("Got message" + o.body());

    // Consumer replies to sender with the same message
    o.reply(o.body());
});

// Now send your messages
for (int i=0;i<messages;i++) {
    JsonObject data = new JsonObject();
    data.put("value", i);

    vertx.eventBus().send("event1", data, response -> {
        if (response.succeeded()) {
            // Each time consumer replies, print it
            System.out.println("Consumer replied: " + response.result().body());
        }
    });
}

Note that the reply is within handler body, and that sender must check that response is successful before accessing it.

Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40