Reputation: 41
I am new to Publish–subscribe pattern, and we are using Vertx in our application.
I am trying to do this for some usecase, where I am publishing inside its own consumer:
private void functionality() {
EventBus eb = Vertx.currentContext().owner().eventBus();
MessageConsumer<String> consumer = eb.consumer("myAddress");
consumer.handler(message -> {
if (condition1) {
doOperationWhichMightChangeTheCondition();
eb.publish("myAddress","Start Operation");
}else {
log.info("Operations on all assets completed");
}
});
eb.publish("myAddress","Start Operation");
}
Is this a bad idea? Can this also lead to StackOverFlow error like recursive calls, or any other issues?
Upvotes: 1
Views: 900
Reputation: 94881
The EventBus.publish
method is asynchronous; it does not block to wait for consumers to receive/process the published message. So it is perfectly safe to call publish
inside a consumer that will then consume the published message. Internally, Vert.x has Netty schedule another call to the consumer, which will not run until the current invocation (and any other methods scheduled ahead of it on the Netty event loop) complete. You can easily prove this to yourself by writing a test that with a consumer that publishes to the address it is consuming from. You won't see a StackOverFlowError
.
Upvotes: 2