KatInterview

Build an Event Dispatcher with Subscribe and Notify Operations

Data Structure DesignModel answer
EasyModel answerData Structure Designevent-systemcallbackserror-handling

Last updated

Design and implement a subscription-based event system where functions can subscribe to event identifiers and be invoked when those events are triggered.

Design and implement an event dispatch mechanism for a single-threaded application. The system allows functions to subscribe to specific event identifiers and be notified when those events occur.

Your implementation must provide three operations:

def register_callback(id, callback) -> None: ...
def unregister_callback(id, callback) -> None: ...
def signal(id) -> None: ...

Where callback can be any callable object in Python.

Example usage:

register_callback(10, handler_a)
register_callback(10, handler_b)
signal(10)  # invokes handler_a and handler_b
unregister_callback(10, handler_b)
signal(10)  # invokes only handler_a
signal(200)  # does nothing since no handlers are registered

Requirements:

  • All three functions must return None
  • Triggering an event with no subscribers should proceed without error
  • Assume single-threaded execution unless told otherwise

Key Design Questions to Consider:

Before implementing, think through:

  • Should signal pass any arguments to the handlers it invokes?
  • If a handler is registered multiple times for the same event, should it execute once or multiple times? How should removal work in that case?
  • What should happen when attempting to remove a handler that was never registered?
  • Must handlers execute in a predictable order?
  • If a handler throws an exception, should subsequent handlers still run?
  • Can a handler itself trigger events? What happens if this creates a cycle?

Your solution should handle these edge cases with explicit, reasoned policies rather than leaving behavior undefined.

Hints

Hint 1

What data structure allows efficient lookup by event ID while maintaining handler ordering?

Hint 2

Consider which Python callables are hashable and which are not (lambdas, bound methods, partials).

Hint 3

Think about reentrancy: a handler calling signal() could create infinite recursion if not detected.