I was talking with someone about their app where they would fire an event that was wired up to multiple listeners, but not all the listeners were relevant for every user of the application.
To make it concrete, and without giving up any proprietary information, think about a hypothetical e-commerce platform where different stores can sign up and sell their products.
When an order is placed, that fires an OrderPlaced
event.
There are multiple listeners for sending an email notification, generating a shipping label, calculating reward points for the purchaser, and so on.
One store might only sell digital products and doesn't need to generate a shipping label. Other stores may use the reward points system, but others don't.
In this case, how would you handle the dynamic nature of events and listeners?
One approach could be to split that single OrderPlaced
event into multiple events and then conditionally dispatch the relevant events based on the store's configuration.
I don't like this approach though. If it really is conceptually a single event, this would add unnecessary complexity and spread the logic around the application to anywhere an order could be generated.
Instead, my approach would be to just fire the single OrderPlaced
event, and wire up all the possible listeners.
Then inside each listener, the first thing I'd do is check and see if this listener is relevant for the store that generated the event.
If it is, I let it run. If not, I exit the listener early with no work done.
This way, the wiring is simple and clear, and the logic for whether it should run is encapsulated entirely in each listener.
Here to help,
Joel
P.S. A quick consultation call like this can help you think through an architectural decision and move forward with more confidence.