CQRS : Apply() vs eventBus.publish()

629 views Asked by At

CQRS patterns like AXON uses apply method inside aggregate which ultimately publishes event to event bus and command handler also has access to eventbus to publish the commandHandled event to eventbus.

What are the pros and cons and when to use what?

1

There are 1 answers

0
Yugang Zhou On BEST ANSWER

Apply method in aggregates usually involves persisting events in the event store in addition to event publishing when adopting event sourcing.

On the other hand, publishing events directly in command handler usually forces your aggregates to expose more details when a command may emit different types of events. For example:

//in command handler
public void handle(FooCommand command) {
    Foo aggregate = //retrieve aggregate
    aggregate.handle(command)

    if (aggregate.isFoo()) {
        eventBus.publish(aFooEvent)
    } else if (aggregate.isBar()) {
        eventBus.publish(aBarEvent)
    }
}