Deviopath › Python

Event Emitter with once()

Hard · Classes

An event emitter lets parts of a program react to named events without knowing about each other, like Node's EventEmitter or addEventListener in the browser. Write a class EventEmitter:

- on(event, listener): register a listener. Registering the same function twice means it runs twice.

- once(event, listener): like on, but the listener is removed automatically right before its first call

- off(event, listener): remove the first registration of that exact function for event, whether it came from on or once. Do nothing if it is not registered.

- emit(event, payload): call the listeners in registration order with payload, and return how many were called

A listener may call on or off while an emit is running. That only affects later emits: the running emit still calls exactly the listeners that were registered when it started (loop over a copy).

The driver run_emitter(ops) is already written. Listeners have ids: each one logs "<id>:<payload>", and every emit logs "<event> -> <count>". A listener whose id starts with off- also removes the listener named by the rest of its id ("off-B" removes B) from the event being emitted.

Next: Sliding Window Rate Limiter