Skip to main content

Observer and Pub/Sub Workshop

Retrieval Prompts

  1. State the three required capabilities of a subject (publisher).
  2. State the minimum interface a classical observer must satisfy.
  3. Name two memory-management hazards of naive Observer and a mitigation for each.
  4. Explain push versus pull notification in one sentence each.
  5. State the line at which Observer becomes Pub/Sub in your mind.

Compare and Distinguish

  • Observer versus direct method call
  • Observer versus Pub/Sub bus with topics
  • push versus pull notification
  • synchronous versus asynchronous notification
  • strong reference versus weak reference to observers

Common Mistake Check

For each snippet, find the bug:

  1. A subject iterates this.listeners directly while calling each update, and a listener calls unsubscribe(self) inside update.
  2. A GUI widget registers itself with a model in its constructor and never unsubscribes.
  3. An update method calls the subject's setter, which re-enters notify.
  4. "Two observers must fire in this order; it works now because I added B after A."
  5. Observer exception bubbles up, subject never notifies the remaining listeners.

Mini Application

Implement these three deliberately, in order:

  1. Classical Observer: a TempSensor with subscribe, unsubscribe, and publish. One observer formats to Celsius, another logs anomalies, a third increments a metric counter.
  2. Defensive Observer: extend the above to snapshot listeners, isolate observer exceptions, and return an unsubscribe token from subscribe.
  3. Topic-based bus: replace the sensor's direct Observer with a small EventBus keyed by topic (temp.updated, temp.anomaly). Show that the sensor no longer knows any subscriber classes.

Contract Drill

For your pub/sub bus:

  1. Define a schema for one event (e.g., OrderPlaced { id, customerId, total, placedAt }).
  2. Write three consumers that rely on it.
  3. Evolve the event (add a field). Which consumers still work? Which need changes?
  4. Write a one-paragraph policy for schema evolution in your bus.

Pitfall Drill

Deliberately cause each failure mode in a controlled test, then fix:

  1. Re-entrant notification that blows the stack.
  2. Subscriber-list mutation during iteration.
  3. Observer leak: subject keeps a dead consumer alive, confirmed by a weak-reference probe.
  4. Silent observer failure: one throws, the rest stop getting notified.

Evidence Check

This page is complete only if you can demonstrate each fix with a test, not by argument.