MediumPro challengePython

Event Bus (Pub/Sub)

PythonDesignEvents

Implement create_event_bus() returning a dict with:

  • subscribe(event, listener) — register a listener, returns an unsubscribe callable.
  • publish(event, data) — call all listeners for the event with data.

solve drives your bus through a sequence of operations and returns
the call log: [[subscriber_id, data], ...].

Operations:

  • ['subscribe', event, id] — subscribe listener id to event.
  • ['publish', event, data] — publish data to event.
  • ['unsubscribe', id] — call the unsubscribe function returned for id.

Sample tests

Test #1Basic subscribe+publish
Input: [[["subscribe","news","s1"],["publish","news","hello"]]]
Output: [["s1","hello"]]
Test #2Unsubscribe stops delivery
Input: [[["subscribe","news","s1"],["publish","news","hello"],["unsubscribe","s1"],["publish","news","world"]]]
Output: [["s1","hello"]]
Test #3Publish with no subscribers
Input: [[["publish","news","nothing"]]]
Output: []
Test #4Two separate events
Input: [[["subscribe","a","s1"],["subscribe","b","s2"],["publish","a",1],["publish","b",2]]]
Output: [["s1",1],["s2",2]]
Test #5Two subscribers to the same event
Input: [[["subscribe","e","s1"],["subscribe","e","s2"],["publish","e",42]]]
Output: [["s1",42],["s2",42]]