dispatch method
Dispatch an event to all registered listeners.
Listeners are executed sequentially to ensure stability and predictable order.
A listener that throws is caught and logged, and the remaining listeners still run. This is a deliberate divergence from Laravel, whose dispatcher lets the exception propagate: on a client, one failing listener must not take down the frame that dispatched the event. The trade is that a broken listener is only visible in the log, so check there when an event looks like it did nothing.
There is no switch to make it rethrow. This docstring used to say the behaviour "can be configured", which was never true.
Implementation
Future<void> dispatch(MagicEvent event) async {
final eventType = event.runtimeType;
// Check strict match
if (!_listeners.containsKey(eventType)) {
return;
}
final listeners = _listeners[eventType]!;
for (final listenerFactory in listeners) {
try {
final listener = listenerFactory();
await (listener as dynamic).handle(event);
} catch (e, stack) {
Log.error('Error handling event $eventType: $e\n$stack');
}
}
}