Mr. Latte


Lesson 3 of 13

Observer: Notify Subscribers

A stock change should update a display and a log. Instead of listing every display type inside the stock object, let interested callbacks register. This is the core idea of Observer.

Subscribe, notify, unsubscribe

class Stock:
    def __init__(self):
        self.quantity = 0
        self.listeners = []
    def subscribe(self, listener):
        self.listeners.append(listener)
    def unsubscribe(self, listener):
        self.listeners.remove(listener)
    def set_quantity(self, quantity):
        self.quantity = quantity
        for listener in list(self.listeners):
            listener(quantity)

def show(quantity):
    print("stock:", quantity)

stock = Stock()
stock.subscribe(show)
stock.set_quantity(3)
stock.unsubscribe(show)
stock.set_quantity(2)

The program prints stock: 3 once. Updating stock to 2 after unsubscription prints nothing. Iterating over a copy keeps the current notification’s recipients stable if a callback changes subscriptions.

Notification policy matters

This example calls listeners synchronously in registration order. Observer does not automatically imply asynchronous execution. A slow or failing listener can affect others; decide whether to propagate errors or handle them individually and continue.

Failing to unsubscribe a closed display can retain unnecessary objects or duplicate notifications. A listener that changes the observed value can also trigger repeated notification loops.

Check your understanding

Every time a display opens, a new callback is registered, but closing it never unsubscribes. What might happen?

Show explanation

One change may trigger the same action repeatedly, or closed displays may remain referenced. Manage subscription start and end as a pair.

Looking for a product partner? Founders, teams, businesses: from problem framing to launch.