In-Process Event Callback Registry
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Build a lightweight single-threaded, in-process publish/subscribe event dispatcher in Python. Listeners (Callable objects taking zero arguments) subscribe under a hashable event key (id), and firing that key runs its subscribed listeners while isolating runtime failures and preventing infinite dispatch loops.
Implement the CallbackRegistry class alongside three module-level convenience functions backed by a default CallbackRegistry instance:
CallbackRegistry(error_handler=log_callback_error)register_callback(id, callback) -> Noneunregister_callback(id, callback) -> Nonesignal(id) -> None
- Module-level functions
register_callback(id, callback) -> None,unregister_callback(id, callback) -> None, andsignal(id) -> None.
Your implementation must enforce all of the following behavioral rules:
- Return values and input validation: Every public method and module function returns
None; any value returned by a listener is discarded.register_callbackmust verifycallable(callback)immediately and raiseTypeErrorif given a non-callable object. - Callable support, ordering, and duplicates: Listeners for a given
idexecute in first-in, first-out (FIFO) registration order. Any Python callable must be supported — including plain functions, bound instance methods (obj.method),functools.partialwrappers, lambdas, and unhashable callable instances (classes defining__call__and__eq__without__hash__). Registering the same listenerktimes causes it to runktimes persignal(id). - Idempotent unregistration:
unregister_callback(id, callback)removes only the earliest matching registration (isor==) forid. Unsubscribing an unknownidor an unsubscribedcallbackdoes nothing (None). - Snapshot dispatch:
signal(id)takes a shallow snapshot ofid's listener list before invoking any listener so mid-dispatchregister_callbackorunregister_callbackcalls take effect starting on the nextsignal(id)call. Firing anidwith zero listeners is a safe no-op. - Failure isolation: If a listener raises an
Exception,signal(id)passes(id, callback, exc)toerror_handlerand continues executing the remaining listeners in the snapshot. Non-Exceptionsubclasses ofBaseException(such asKeyboardInterruptorSystemExit) must propagate out immediately without leavingidstuck in an active state. - Cycle prevention (
ReentrantSignalError): A listener may legitimately callsignal(other_id)for a distinct inactive key, forming acyclic chains. However, callingsignal(id)whileidis already mid-dispatch anywhere on the current call stack — either directly (id -> id) or indirectly (k1 -> k2 -> k1) — must immediately raiseReentrantSignalError.
Examples
Example 1
Input:
events = []
def record_audit():
events.append("audit")
def send_alert():
events.append("alert")
register_callback(42, record_audit)
register_callback(42, send_alert)
signal(42)
unregister_callback(42, send_alert)
signal(42)
signal(999)
Output:
# Every call returns None, and `events` ends up as:
["audit", "alert", "audit"]
Walk-through: Subscribing record_audit then send_alert under key 42 and calling signal(42) runs both in FIFO order (["audit", "alert"]). After unregister_callback(42, send_alert), the second signal(42) runs only record_audit (["audit", "alert", "audit"]), and signal(999) is a no-op because key 999 has no subscribers.
Example 2
Input:
logged_errors = []
trace = []
reg = CallbackRegistry(error_handler=lambda sig, cb, exc: logged_errors.append((sig, type(exc).__name__)))
reg.register_callback("sync", lambda: trace.append("start"))
reg.register_callback("sync", lambda: (_ for _ in ()).throw(ValueError("bad row")))
reg.register_callback("sync", lambda: (trace.append("finish"), reg.signal("notify")))
reg.register_callback("notify", lambda: trace.append("notified"))
reg.signal("sync")
reg.register_callback("s1", lambda: (trace.append("s1"), reg.signal("s2")))
reg.register_callback("s2", lambda: (trace.append("s2"), reg.signal("s1")))
reg.signal("s1")
Output:
# trace:
["start", "finish", "notified", "s1", "s2"]
# logged_errors:
[("sync", "ValueError"), ("s2", "ReentrantSignalError")]
Walk-through: During reg.signal("sync"), the second listener raises ValueError, which is reported to error_handler while the third listener still runs and chains cleanly into "notify". Next, reg.signal("s1") chains into "s2", whose attempt to re-trigger active key "s1" raises ReentrantSignalError; "s2"'s dispatch loop reports that error and unwinds cleanly without infinite recursion.
Constraints
idis any hashable Python object (int,str,tuple, enum, etc.).callbackmay be any callable object (not necessarily hashable); non-callable values passed toregister_callbackmust raiseTypeError.- Single-threaded execution may be assumed for the core implementation.
- Up to
10^4total registrations andsignalinvocations per test run.
Step-by-step walkthrough
Clarify the contract before writing code
A publish/subscribe (pub/sub) registry is an event board where listener functions ("subscribers" or callbacks) sign up under a topic key (
id), and firing that key (signal(id)) invokes every function signed up for it.Because the implementation is compact, the real design work is locking down crisp, defensible rules for every ambiguous interaction up front:
Design question Chosen rule Why this rule makes sense What arguments does signal(id)pass to listeners?Zero arguments: callback()signal(id)carries no payload. Callers needing context can bind arguments viafunctools.partial(fn, id).What if the same listener subscribes twice under one id?Keep both; invoke twice; one unregister_callbackremoves the earliest copyTwo subsystems may register the same helper independently; one subsystem cleaning up should not silently disable the other. What if unregister_callbackreceives an unknownidor listener?Safe no-op ( return None)Makes finallyand teardown blocks idempotent (safe to execute repeatedly without crashing).Which types are valid for idandcallback?idis hashable;callbackis any callableidserves as a dictionary key. Checkingcallable(callback)eagerly catches bad inputs at registration rather than mid-dispatch.Where do listener exceptions go when signal()returnsNone?Forward (id, callback, exc)toerror_handlerPrevents one broken listener from starving later ones while surfacing failures in logs or unit tests. Why a dictionary of lists beats a dictionary of sets
We need a per-key container mapping each
idto its subscribed listeners. A hashable object has a fixed hash code so Python can place it inside asetor use it as adictkey. Storing listeners inside aset(dict[id, set]) looks tempting forO(1)deletion, yet it breaks three requirements at once:- Unhashable callables crash registration: A custom class defining
__call__and__eq__(without__hash__) is a valid Python callable (any object invocable with()), yet Python marks it unhashable, soset.add(cb)raisesTypeError: unhashable type. - Duplicates vanish: Subscribing
[f, g, f]in asetsilently drops the secondf. - No FIFO ordering guarantee: Python's
setdoes not preserve insertion order, whereas callers expect FIFO execution.
Using
Dict[Hashable, List[Callable]]handles all three cleanly. When removing a listener from the list, we check identity (is) followed by equality (==). In Python, evaluatingobj.methodallocates a fresh bound method wrapper (pairingselfwith the underlying function) on every attribute access:Lookup 1: register_callback(42, counter.hit) -> creates wrapper_A(self=counter, func=hit) Lookup 2: unregister_callback(42, counter.hit) -> creates wrapper_B(self=counter, func=hit) wrapper_A is wrapper_B -> False (distinct wrapper allocations!) wrapper_A == wrapper_B -> True (same `self` and same underlying function)Note that two separate
lambdaexpressions or twofunctools.partial(tag, "p")instances compare by identity (==isFalse), so callers using lambdas or partials must hold onto the exact object they registered.Operation Cost Work done (m = listeners subscribed to that id) register_callback O(1)* dict lookup + list append (*amortized) unregister_callback O(m) scan at most m items on that id + list delete signal O(m) copy the m-item list + invoke each listener- Unhashable callables crash registration: A custom class defining
Implement registration and safe unregistration
Encapsulate state inside
CallbackRegistryso tests can instantiate isolated registries with custom error recorders, and expose the three module-level functions delegating to a shared_registry.Inside
unregister_callback, checkingregistered_cb is callbackbeforeregistered_cb == callbackmirrors Python'slist.remove: fast pointer check first, value equality second. When the last listener for anidis deleted, removeidfromself._callbacksso retired keys do not accumulate in memory.class CallbackRegistry: def __init__(self, error_handler: Callable = log_callback_error) -> None: # _callbacks: maps signal_id -> list of callables in registration order, # e.g. {42: [record_audit, send_alert], "sync": [on_finish]} self._callbacks: Dict[Hashable, List[Callable]] = {} # _in_flight: set of signal_ids currently mid-dispatch on the call stack, # e.g. {"s1", "s2"}, used to catch direct (42 -> 42) and indirect (s1 -> s2 -> s1) cycles self._in_flight: Set[Hashable] = set() # _error_handler: side-channel callback invoked as error_handler(id, callback, exc) # because signal() itself must return None self._error_handler = error_handler def register_callback(self, id: Hashable, callback: Callable) -> None: # Validate eagerly so non-callable values fail at registration time, not inside signal(). if not callable(callback): raise TypeError(f"callback must be callable, got {callback!r}") if id not in self._callbacks: self._callbacks[id] = [] self._callbacks[id].append(callback) def unregister_callback(self, id: Hashable, callback: Callable) -> None: callbacks = self._callbacks.get(id) if callbacks is None: # Unknown id is a safe no-op so cleanup/teardown code can run multiple times safely. return # Scan in order so one unregister removes only the earliest matching registration. for index, registered_cb in enumerate(callbacks): # Check `is` first, then `==`: accessing `obj.method` creates a new bound-method # object each time (`is` is False), whereas `==` compares (self, underlying_func). if registered_cb is callback or registered_cb == callback: del callbacks[index] break # Remove empty lists so unused signal ids do not accumulate in memory over time. if not callbacks: del self._callbacks[id]Isolate failing callbacks without breaking Ctrl-C
Consider what happens when the middle listener in
[on_start, broken_sync, on_finish]raisesValueError("bad row"):- Abort and re-raise:
on_finishnever executes, and the publisher callingsignal()crashes because of an unrelated subscriber. - Swallow silently (
pass):on_finishexecutes, but the defect inbroken_syncvanishes without a trace. - Isolate and report (chosen policy): catch the error around each individual
callback(), pass(id, callback, exc)toself._error_handler, and continue the loop soon_finishstill runs. By default,log_callback_errorlogs the full traceback.
Be selective about which exceptions are caught. In Python's hierarchy, application errors (
ValueError,KeyError,RuntimeError) inherit fromException, whereas process-termination interrupts (KeyboardInterrupton Ctrl-C andSystemExit) inherit directly fromBaseException. CatchingExceptionisolates broken listeners while allowing Ctrl-C to halt the process immediately.class ReentrantSignalError(RuntimeError): """signal(id) was called while the same id was already being dispatched.""" def log_callback_error(signal_id: Hashable, callback: Callable, exc: Exception) -> None: """Default error handler: log the failure with its traceback and carry on.""" logger.error("callback %r for signal %r raised", callback, signal_id, exc_info=exc)- Abort and re-raise:
Stop infinite loops with a snapshot and an in-flight set
Two subtle hazards arise while
signal(id)is mid-way through invoking its listeners:1. Mid-dispatch subscription edits. Suppose
[once, h]are subscribed, andoncecallsunregister_callback(1, once)while executing. Iterating directly over the live list shiftshleft from index1to index0right before the loop advances to index1— skippinghcompletely!Live list mutation bug: start: callbacks = [once, h] loop at index 0 -> runs once() inside: del callbacks[0] callbacks is now [h] (h shifted to index 0!) next: loop moves to index 1 past the end -> h never runs! Snapshot fix: start: snapshot = [once, h] live self._callbacks[1] can change freely; current signal finishes [once, h], and edits apply on the NEXT signal(1).2. Reentrant dispatch cycles. Reentrancy occurs when a routine is invoked again before an earlier invocation has finished. Chaining distinct keys (
"sync"triggers"notify"in Example 2) is useful, whereas re-firing a key that is still active on the call stack — directly (42 -> 42) or indirectly ("s1" -> "s2" -> "s1") — recurses endlessly untilRecursionError.We guard active keys using
self._in_flight: - Before iteratingsnapshot, checkif id in self._in_flight:and raiseReentrantSignalError. - Otherwise addidtoself._in_flight, run the loop, and discardidinside afinallyblock so even an uncatchableKeyboardInterruptcleans up the active marker.Why every
signal()call is guaranteed to terminate overKregistered keys: - Each nestedsignal(next_id)either hits an empty key (returns immediately), hits a key already in_in_flight(raisesReentrantSignalErrorimmediately), or adds one hitherto-inactive key to_in_flight. - Since_in_flightcan hold at mostKkeys simultaneously, call depth is bounded byK, and each frame iterates over a finitesnapshotlist.def signal(self, id: Hashable) -> None: # Reject reentrant cycles if this id is already active on the current call stack. if id in self._in_flight: raise ReentrantSignalError(f"signal {id!r} is already being dispatched") callbacks = self._callbacks.get(id) if not callbacks: return # Iterate over a shallow copy so register/unregister calls inside a callback # take effect on the next signal() instead of shifting indices mid-loop. snapshot = list(callbacks) # Always clear the in-flight mark in `finally` so an uncatchable BaseException # (like KeyboardInterrupt) cannot leave this id permanently locked out. self._in_flight.add(id) try: for callback in snapshot: try: callback() except Exception as exc: # Catch Exception (not BaseException) so one broken callback cannot # starve later ones, while Ctrl-C and SystemExit still propagate. self._error_handler(id, callback, exc) finally: self._in_flight.discard(id)Trace Example 1 and Example 2 step by step
First, trace Example 1 (
42and999):Call _callbacks _in_flight What runs register_callback(42, record_audit) {42: [record_audit]} set() - register_callback(42, send_alert) {42: [record_audit, send_alert]} set() - signal(42) {42: [record_audit, send_alert]} {42} -> {} record_audit(), send_alert() unregister_callback(42, send_alert) {42: [record_audit]} set() - signal(42) {42: [record_audit]} {42} -> {} record_audit() signal(999) {42: [record_audit]} set() nothing (no-op)Second, trace the
"s1" -> "s2" -> "s1"cycle from Example 2:1. reg.signal("s1") _in_flight = {"s1"} runs cb_s1() -> appends "s1", calls reg.signal("s2") 2. reg.signal("s2") _in_flight = {"s1", "s2"} runs cb_s2() -> appends "s2", calls reg.signal("s1") 3. reg.signal("s1") "s1" is in _in_flight! -> raises ReentrantSignalError 4. "s2" loop catches ReentrantSignalError -> error_handler("s2", cb_s2, err) 5. finally discards "s2", then outer finally discards "s1" -> _in_flight = set(), returns NoneComplete solution
from typing import Callable, Dict, Hashable, List, Set import logging logger = logging.getLogger(__name__) class ReentrantSignalError(RuntimeError): """signal(id) was called while the same id was already being dispatched.""" def log_callback_error(signal_id: Hashable, callback: Callable, exc: Exception) -> None: """Default error handler: log the failure with its traceback and carry on.""" logger.error("callback %r for signal %r raised", callback, signal_id, exc_info=exc) class CallbackRegistry: def __init__(self, error_handler: Callable = log_callback_error) -> None: # _callbacks: maps signal_id -> list of callables in registration order, # e.g. {42: [record_audit, send_alert], "sync": [on_finish]} self._callbacks: Dict[Hashable, List[Callable]] = {} # _in_flight: set of signal_ids currently mid-dispatch on the call stack, # e.g. {"s1", "s2"}, used to catch direct (42 -> 42) and indirect (s1 -> s2 -> s1) cycles self._in_flight: Set[Hashable] = set() # _error_handler: side-channel callback invoked as error_handler(id, callback, exc) # because signal() itself must return None self._error_handler = error_handler def register_callback(self, id: Hashable, callback: Callable) -> None: # Validate eagerly so non-callable values fail at registration time, not inside signal(). if not callable(callback): raise TypeError(f"callback must be callable, got {callback!r}") if id not in self._callbacks: self._callbacks[id] = [] self._callbacks[id].append(callback) def unregister_callback(self, id: Hashable, callback: Callable) -> None: callbacks = self._callbacks.get(id) if callbacks is None: # Unknown id is a safe no-op so cleanup/teardown code can run multiple times safely. return # Scan in order so one unregister removes only the earliest matching registration. for index, registered_cb in enumerate(callbacks): # Check `is` first, then `==`: accessing `obj.method` creates a new bound-method # object each time (`is` is False), whereas `==` compares (self, underlying_func). if registered_cb is callback or registered_cb == callback: del callbacks[index] break # Remove empty lists so unused signal ids do not accumulate in memory over time. if not callbacks: del self._callbacks[id] def signal(self, id: Hashable) -> None: # Reject reentrant cycles if this id is already active on the current call stack. if id in self._in_flight: raise ReentrantSignalError(f"signal {id!r} is already being dispatched") callbacks = self._callbacks.get(id) if not callbacks: return # Iterate over a shallow copy so register/unregister calls inside a callback # take effect on the next signal() instead of shifting indices mid-loop. snapshot = list(callbacks) # Always clear the in-flight mark in `finally` so an uncatchable BaseException # (like KeyboardInterrupt) cannot leave this id permanently locked out. self._in_flight.add(id) try: for callback in snapshot: try: callback() except Exception as exc: # Catch Exception (not BaseException) so one broken callback cannot # starve later ones, while Ctrl-C and SystemExit still propagate. self._error_handler(id, callback, exc) finally: self._in_flight.discard(id) _registry = CallbackRegistry() def register_callback(id, callback) -> None: _registry.register_callback(id, callback) def unregister_callback(id, callback) -> None: _registry.unregister_callback(id, callback) def signal(id) -> None: _registry.signal(id)✅ Submit now — all tests should pass.
Intuition & how it works
Think of this registry like an office dispatch board organized by event code (id), where each event code holds a numbered sign-up sheet of listener functions (callbacks) to invoke in the exact order they subscribed.
A naive implementation drops listeners into a Python set and loops directly over that container inside signal(id). That fails immediately: a set crashes with TypeError on unhashable callable objects (objects without a fixed hash code), loses sign-up order, and silently collapses intentional duplicate subscriptions. Worse, iterating over a live list skips the next listener whenever an executing listener unsubscribes itself, and allowing a listener to re-fire an event code that is still mid-dispatch causes unbounded recursion.
Instead, we map id -> list[Callable], copy that list into a snapshot (a shallow copy frozen at the start of dispatch) before invoking anything, wrap each invocation in try ... except Exception so one crash cannot starve later subscribers, and track active dispatches in an _in_flight set. For example, with [record_audit, send_alert] subscribed under key 42:
1. signal(42) checks 42 in _in_flight (False), copies snapshot = [record_audit, send_alert], and adds 42 to _in_flight.
2. If record_audit() accidentally calls signal(42) again, the nested call sees 42 in _in_flight and raises ReentrantSignalError.
3. The outer loop catches that Exception, forwards (42, record_audit, err) to error_handler, still executes send_alert(), and discards 42 from _in_flight inside finally.
Complexity
register_callback: O(1) amortized time. One dictionary lookup byidplus an amortized constant-timelist.append.unregister_callback: O(m) time, wheremis the number of listeners registered under that specificid. In the worst case we scan allmentries on thatidto locate the earliest match and shift subsequent pointers left ondel, never touching other event keys.signal: O(m) dispatch overhead (plus the runtime of themlisteners themselves). Membership checks and updates on_in_flighttake O(1) set operations, andlist(callbacks)copiesmcallable references once prior to looping.- Space: O(N + K) overall, where
Nis the total number of active listener registrations acrossKactive event keys (plus at mostKkeys inside_in_flightduring nested chains). Empty lists are pruned on unregistration so retired keys consume zero memory.
Edge cases
- Signaling an unknown key (
signal(999)):_callbacks.get(999)isNone, sosignalreturnsNoneimmediately without error. - Duplicate subscriptions (
[f, g, f]):signalinvokesf, theng, thenf. Oneunregister_callbackremoves only the earliestf, leaving[g, f]. - Unsubscribing an unknown key or listener: safely ignored as a no-op, including when
fis subscribed under key1and the caller unsubscribes(2, f). - Bound methods (
obj.method): every attribute evaluationobj.methodallocates a fresh bound method wrapper (obj.method is obj.methodisFalse), sounregister_callbackfalls back to==to compare the underlying(self, function)pair. - Lambdas and
functools.partial: two separatelambdaorpartial(tag, "p")instances compare by object identity, so callers must retain the exact object they passed toregister_callbackif they later wish to unsubscribe it. - Unhashable callable instances: a class defining
__call__and__eq__(which sets__hash__ = Nonein Python) works smoothly because listeners live in lists rather than sets or dict keys. KeyboardInterruptandSystemExit: because the dispatch loop catchesExceptionrather thanBaseException, process-level interrupts propagate out immediately whilefinallystill removesidfrom_in_flight.- Unbounded chains of newly minted keys: if listener
ndynamically registers and fires keyn + 1forever,_in_flightsees no repeated key and Python eventually raisesRecursionError(caught as anException). Enforcingif len(self._in_flight) >= MAX_DEPTH:converts that into an immediateReentrantSignalError.
Common mistakes
- Storing listeners in a
set: loses FIFO order, collapses valid duplicate subscriptions, and raisesTypeErroron unhashable callable instances. - Checking only
isinunregister_callback:unregister_callback(42, counter.hit)fails to match the earliercounter.hitwrapper, leaving the listener subscribed forever. - Iterating directly over
self._callbacks[id]withoutlist(...): if listeneriunsubscribes itself, elementi + 1shifts left into indexiand gets skipped on the next iteration. - Using bare
except:orexcept BaseException:: swallowsKeyboardInterrupt(Ctrl-C) andSystemExitinside the dispatch loop. - Clearing
_in_flightoutside afinallyblock: if an uncatchableBaseExceptionescapes mid-dispatch,idremains stuck in_in_flightand every futuresignal(id)falsely raisesReentrantSignalError. - Forbidding all nested
signal()calls: a single boolean_dispatchingflag breaks valid multi-stage pipelines such as"sync" -> "notify". Tracking a set of active keys blocks cycles while permitting acyclic chains.
Alternative approaches
- Subscription token / handle:
register_callbackreturns an opaque integer ID (or aSubscriptionobject with.cancel()), enabling O(1) unsubscription and unambiguous removal of inline lambdas — traded off here because the API requiresregister_callbackto returnNone. - Ordered count map (
dict[id, dict[Callable, int]]): gives O(1) unsubscription and preserves first-seen order, but rejects unhashable callables and alters interleaved duplicates ([f, g, f]executes asf, f, g). - Strict unsubscription errors: raising
KeyErrororValueErrorwhenunregister_callbackfinds no match catches caller typos early, at the expense of idempotentfinallycleanup.
Follow-up questions
- Suppose an active listener unsubscribes itself—or subscribes a new listener to the same signal key—mid-dispatch. How does your design behave, and when would you tighten that contract? Because
signalloops oversnapshot = list(callbacks)captured before the first listener runs, both self-unsubscription and new subscriptions take effect starting on the nextsignal(id)call, eliminating index-shift skips. The one subtlety is when listener A unsubscribes listener B mid-dispatch: under pure snapshot semantics, B still executes one final time in the in-progress batch. When strict "never fires onceunregister_callbackreturns" guarantees are needed, wrap each listener in a small_Slot(callback, active=True)record —unregister_callbacksetsslot.active = Falseand deletes it from the live list, whilesignalchecksif slot.active:before calling each snapshot slot.
python
class _Slot:
def __init__(self, callback: Callable) -> None:
self.callback = callback
self.active = True # cleared on unregister so in-progress snapshots skip it
-
How would you adapt this registry for multi-threaded callers without risking deadlocks when a listener re-enters the registry? Guard
self._callbackswith a mutex lock (threading.Lock, a synchronization primitive allowing only one thread at a time to read or mutate shared state), hold that lock only while copyingsnapshot = list(callbacks), and release it before invoking any user listener. Never invoke arbitrary subscriber code while holding a lock: even with a reentrant lock (threading.RLock, which the owning thread can re-acquire), two threads cross-signaling or waiting on each other inside listeners will deadlock. Equally important, move_in_flightinto thread-local storage (threading.local(), giving each OS thread its own isolated active set), since Thread A and Thread B firing key42simultaneously is concurrent execution rather than a recursive loop. -
Storing normal references to bound methods prevents their owning instances from being garbage-collected. How can you eliminate that retention leak, and what caveats appear? A weak reference tracks an object without preventing Python's garbage collector from reclaiming it once all normal references disappear. You can wrap bound methods with
weakref.WeakMethod(cb)(note that plainweakref.ref(obj.method)dies immediately because the temporary bound-method wrapper has no other owner!) and regular callables withweakref.ref(cb), dereferencing each entry duringsignaland pruning dead references that returnNone. Two caveats follow: ephemeral callables passed inline — such asregister_callback(42, lambda: ...)or an unsavedfunctools.partial— have zero external owners and get collected right away without ever firing, and classes using__slots__without"__weakref__"raiseTypeError. Consequently, production event buses keep strong references by default and expose an explicitweak=Trueoption.
Follow-up questions
- Suppose an active listener unsubscribes itself—or subscribes a new listener to the same signal key—mid-dispatch. How does your design behave, and when would you tighten that contract?
- How would you adapt this registry for multi-threaded callers without risking deadlocks when a listener re-enters the registry?
- Storing normal references to bound methods prevents their owning instances from being garbage-collected. How can you eliminate that retention leak, and what caveats appear?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes