AlgoViz

Observer pattern

medium 50 min

Decouple a state-holding subject from its dependents: they register, and the subject notifies everyone on its list when something changes.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:58

See it run

Who is on the list, who is called, and what can happen during a round.

Operations

Weather station

Register, change, notify, leave. Arrows are the entries of the list.

Step 1 of 10

Nobody listens

clientClientstationWeatherStationtemperature72 Fhumidity65 %observers0phonePhoneDisplayshowswebWebDashboardpoints0mailEmailAlertsent0

Nobody is told

The station knows 72 F and 65 percent. The list is empty.

Step 1: Nobody listens

class WeatherStation:    def attach(self, o):        self._observers.append(o)    def detach(self, o):        self._observers.remove(o)    def set_measurements(self, t, h):        self._temperature, self._humidity = t, h        for o in list(self._observers):            o.update(t, h)class PhoneDisplay:    def update(self, t, h):        self.show(t)
Watch
The arrows
Result
Only those on the list

No arrow leads to a class the station knows by name.

In the real world

The same observer pattern doing real jobs. Pick one and step through it.

Settings live long, dialogs live short.

Step 1 of 4

Open

screenWindowsettingsSubjectobservers1dialog 1Dialogpictures5 MB

Dialog 1 attaches.

Step 1: Open

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Looping over the live list

    critical

    Who leaves during a round makes the next one skipped, or Java throws.

    Wrong
    for o in self._observers:    o.update(v)
    Right
    for o in list(self._observers):    if o in self._observers:        o.update(v)
  • Notify before store

    critical

    An observer that asks back gets the old value.

    Wrong
    self._notify(new)self._value = new
    Right
    self._value = newself._notify(new)
  • Nobody detaches

    critical

    The observer is never freed and goes on reacting.

    Wrong
    settings.attach(dialog.on_change)
    Right
    self._stop = settings.attach(self.on_change)# and in close():self._stop()
  • Swallowed errors

    major

    A broken observer looks healthy.

    Wrong
    except Exception:    pass
    Right
    except Exception as error:    self._on_error(event, error)
  • Calling under a lock

    critical

    Two locks can wait for each other.

    Wrong
    with self._lock:    for o in self._observers:        o.update(v)
    Right
    with self._lock:    round = tuple(self._observers)for o in round:    o.update(v)
  • A step disguised as an observer

    major

    If reserving stock fails, nobody stops the order.

    Wrong
    order.paid.attach(reserve_stock)
    Right
    reserve_stock(order)      # a stepcommit(order)order.paid.notify(order)  # reactions

Interview tips

  • A safe round

    • Store first.
    • Copy the list.
    • Catch each call.
  • Leaving

    • Attach returns a handle.
    • An owner closes it.
    • Twice is harmless.
  • The message

    • Immutable.
    • Past tense.
    • Equal is not news.
  • Threads

    • No lock in calls.
    • Bounded queues.
    • A rule for dropping.
  • Is it an observer?

    • Result matters: step.
    • Order matters: step.
    • Otherwise: react.