📤 EventEmitter¶
The EventEmitter is a core component of Dispytch used to publish events to an underlying message broker such as
RabbitMQ, Kafka, or Redis. It abstracts away the details of the producer backend and allows you to send events
with minimal boilerplate.
✅ Why do I need it?¶
-
Separation of concerns: Your app’s business logic shouldn’t wrestle with raw message brokers.
EventEmitterabstracts away the gritty details of RabbitMQ, Kafka, or whatever it is under the hood, so you can focus on events—not infrastructure. -
Consistency & safety: Typed events with
EventBaseensure your payloads are validated and predictable. -
Multiple backends: Whether you want to use Kafka or RabbitMQ,
EventEmitterlets you switch between or postpone backend decisions with substantially less overhead. -
Testability: Emitting an event is just calling a method on an object you can mock or swap out—making your code easier to test and reason about.
Bottom line: EventEmitter turns event publishing into a streamlined, reliable, and
developer-friendly interface. Without it, you’re stuck juggling broker APIs, serialization, and error-prone glue code.
🧱 Basic Structure¶
1 2 | |
EventEmitter expects a Producer instance (such as RabbitMQProducer or KafkaProducer) that handles the actual
transport layer.
🧾 Event Definition¶
-
MyEventinherits fromEventBaseand defines:__route__: Target route for the event.__backend_config__: See Backend-Specific Configuration.- Event payload fields using standard
pydanticmodel syntax.
Example:
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 | |
✍️ Example: Setting Up Event Emitter¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
⚠️ Important:
When using Kafka with EventEmitter, you must manually start the underlying AIOKafkaProducer. Dispytch does not start it for you.
If you forget to call:
1 | |
events will not be published, and you won’t get any errors—they’ll just silently vanish into the void.
So don’t skip it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
⚠️ Important:
When using RedisProducer with EventEmitter, you should pass the asyncio-compatible Redis client (from redis.asyncio) to the producer.
⏱️ Handling Timeouts with on_timeout¶
By default, if an event fails to emit due to a timeout, Dispytch logs a warning. If you want custom behavior (e.g.,
metrics, retries, alerts), you can register a callback using on_timeout():
1 2 3 | |
The callback can be sync or async, and receives the original EventBase instance that timed out.