Bird
Raised Fist0

What will be the output after these operations?

medium🧾 Code Trace Q4 of Q15
OOP & Design Patterns - Observer Pattern - Event System, Publish-Subscribe
Consider the following thread-safe observer pattern code snippet. What will be the output after these operations? ```python subject = Subject() obs = Observer('Obs') subject.subscribe(obs, 'eventX') subject.unsubscribe(obs, 'eventX') subject.notify('eventX', 'Test') ``` Assuming notify calls update on all subscribed observers for the event type.
AError due to empty observer list
BObs received eventX: Test
CNo output
DObs received eventX: Test twice
Step-by-Step Solution
Solution:
  1. Step 1: Trace unsubscribe

    Observer is removed from eventX's observer set; if empty, the event key is deleted.
  2. Step 2: Trace notify

    Notify checks if eventX exists; since it was deleted, no observers exist, so no update calls.
  3. Step 3: Consider concurrency

    Without concurrency issues, no error occurs; notify simply does nothing.
  4. Final Answer:

    Option C -> Option C
  5. Quick Check:

    Unsubscribe deletes event key; notify finds no observers and produces no output [OK]
Quick Trick: Unsubscribe deletes event key; notify finds no observers [OK]
Common Mistakes:
MISTAKES
  • Assuming error occurs
  • Ignoring key deletion
  • Expecting output despite unsubscribe
Trap Explanation:
PITFALL
  • Candidates often think no output occurs, but without thread safety, notify can raise errors; here code is single-threaded, so no error.
Interviewer Note:
CONTEXT
  • Tests understanding of unsubscribe and notify behavior in observer pattern.
Master "Observer Pattern - Event System, Publish-Subscribe" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes