Polski

Article · Observer · Event-Driven Architecture

Observer: notify everyone without knowing anyone

The Observer pattern through a pierogi place's pantry: when the cheese runs out, the menu, the shopping list and alerts react on their own, and the pantry does not know they exist. Subscribing, unsubscribing, pitfalls and code in five languages.

By · · 13 min read

In Halina's pierogi place the farmer's cheese always runs out at the worst moment. When the stock drops to zero, the potato-and-cheese pierogi have to disappear from the menu, cheese has to go onto the shopping list and – at weekends – Halina gets a text message. Observer lets the pantry announce a change and lets the interested parties react on their own, without knowing about each other.

1 → N
one subject, many receivers – the number of observers is not known up front
0
receiver imports in the subject – the pantry does not know who is listening
3
typical pitfalls – leaks, ordering and exceptions in observers

The problem: a pantry that knows too much

The first version of the pantry called everyone interested directly:

pantry-before.ts
class Pantry {
  constructor(
    private readonly menu: MenuBoard,
    private readonly shopping: ShoppingList,
    private readonly sms: SmsGateway,
  ) {}

  use(ingredient: string, amount: number): void {
    const current = this.decrease(ingredient, amount);
    if (current === 0) this.menu.hideDishesWith(ingredient);
    if (current < 3) this.shopping.add(ingredient);
    if (current < 3 && isWeekend()) this.sms.send('+48 600 000 000', `Low on ${ingredient}!`);
    // next sprint: loyalty app, kitchen display, weekly report...
  }
}

The Pantry class depends on the menu, the shopping list and the SMS gateway. Every new receiver – a loyalty app, a kitchen display, a weekly report – means another constructor parameter and another if in a method that was only supposed to decrease the stock. Unit tests of the pantry need fakes of three unrelated services, and an SMS gateway outage can break taking an ingredient off the stock.

The solution: announce the change, do not call the recipients

The pantry stops calling concrete classes. Instead it offers a subscription: anyone interested registers a function or an object with an onStockChanged method. When the stock changes, the pantry walks the list and notifies everyone – without knowing whether the other side is the menu, an SMS or a unit test.

Diagram: One state change, three receivers
Diagram: The structure of the Observer pattern
RoleIn the exampleResponsibility
SubjectPantrykeeps subscriptions and announces changes
ObserverStockListener / function typethe common interface for reacting to a change
Concrete observerMenuBoard, ShoppingList, SmsAlertdoes something with the notification, unaware of the others
EventStockChangechange data: ingredient, previous and current stock

Implementation in five languages

In C# the pattern is built into the language as event; in TypeScript and Python a set of functions is enough; in Java it is a list of listeners; in Go a map of functions guarded by a mutex. In every variant subscribing returns a way to unsubscribe.

Observer – pantry stock

Pantry.cs
var pantry = new Pantry();
var menu = new MenuBoard();
pantry.StockChanged += menu.OnStockChanged;
pantry.StockChanged += (_, e) =>
{
    if (e.Current < 3) Console.WriteLine($"Shopping list: buy {e.Ingredient}");
};

pantry.Use("cheese", 4);                    // menu hides dishes, shopping list reacts
pantry.StockChanged -= menu.OnStockChanged; // always unsubscribe long-lived subjects
pantry.Restock("cheese", 10);

public sealed record StockChange(string Ingredient, int Previous, int Current);

public sealed class Pantry
{
    private readonly Dictionary<string, int> _stock = new() { ["cheese"] = 4, ["potatoes"] = 20 };

    // The subject only knows the delegate type, not the subscribers.
    public event EventHandler<StockChange>? StockChanged;

    public void Use(string ingredient, int amount) => Set(ingredient, Stock(ingredient) - amount);
    public void Restock(string ingredient, int amount) => Set(ingredient, Stock(ingredient) + amount);

    private int Stock(string ingredient) => _stock.GetValueOrDefault(ingredient);

    private void Set(string ingredient, int current)
    {
        var previous = Stock(ingredient);
        if (previous == current) return;
        _stock[ingredient] = current;
        StockChanged?.Invoke(this, new StockChange(ingredient, previous, current));
    }
}

public sealed class MenuBoard
{
    public void OnStockChanged(object? sender, StockChange e)
    {
        if (e.Current == 0) Console.WriteLine($"Menu: hiding dishes with {e.Ingredient}");
        else if (e.Previous == 0) Console.WriteLine($"Menu: dishes with {e.Ingredient} are back");
    }
}
pantry.ts
type StockChange = { ingredient: string; previous: number; current: number };
type Listener = (change: StockChange) => void;

class Pantry {
  private readonly stock = new Map<string, number>([['cheese', 4], ['potatoes', 20]]);
  private readonly listeners = new Set<Listener>();

  /** Returns a function that unsubscribes the listener. */
  subscribe(listener: Listener): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  use(ingredient: string, amount: number): void {
    this.set(ingredient, (this.stock.get(ingredient) ?? 0) - amount);
  }

  restock(ingredient: string, amount: number): void {
    this.set(ingredient, (this.stock.get(ingredient) ?? 0) + amount);
  }

  private set(ingredient: string, current: number): void {
    const previous = this.stock.get(ingredient) ?? 0;
    if (previous === current) return;
    this.stock.set(ingredient, current);
    // Iterate over a copy, so a listener may unsubscribe while being notified.
    for (const listener of [...this.listeners]) listener({ ingredient, previous, current });
  }
}

const pantry = new Pantry();
const stopMenu = pantry.subscribe(({ ingredient, previous, current }) => {
  if (current === 0) console.log(`Menu: hiding dishes with ${ingredient}`);
  else if (previous === 0) console.log(`Menu: dishes with ${ingredient} are back`);
});
pantry.subscribe(({ ingredient, current }) => {
  if (current < 3) console.log(`Shopping list: buy ${ingredient}`);
});

pantry.use('cheese', 4); // menu hides dishes, shopping list reacts
stopMenu();
pantry.restock('cheese', 10); // the menu no longer hears about it
Kitchen.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

record StockChange(String ingredient, int previous, int current) {}

@FunctionalInterface
interface StockListener {
    void onStockChanged(StockChange change);
}

class Pantry {
    private final Map<String, Integer> stock = new HashMap<>(Map.of("cheese", 4, "potatoes", 20));
    // Safe to iterate while listeners subscribe or unsubscribe.
    private final List<StockListener> listeners = new CopyOnWriteArrayList<>();

    /** Returns a handle that unsubscribes the listener when closed. */
    AutoCloseable subscribe(StockListener listener) {
        listeners.add(listener);
        return () -> listeners.remove(listener);
    }

    void use(String ingredient, int amount) { set(ingredient, stock.getOrDefault(ingredient, 0) - amount); }

    void restock(String ingredient, int amount) { set(ingredient, stock.getOrDefault(ingredient, 0) + amount); }

    private void set(String ingredient, int current) {
        int previous = stock.getOrDefault(ingredient, 0);
        if (previous == current) return;
        stock.put(ingredient, current);
        var change = new StockChange(ingredient, previous, current);
        listeners.forEach(l -> l.onStockChanged(change));
    }
}

public class Kitchen {
    public static void main(String[] args) throws Exception {
        var pantry = new Pantry();
        var menu = pantry.subscribe(c -> {
            if (c.current() == 0) System.out.println("Menu: hiding dishes with " + c.ingredient());
            else if (c.previous() == 0) System.out.println("Menu: dishes with " + c.ingredient() + " are back");
        });
        pantry.subscribe(c -> {
            if (c.current() < 3) System.out.println("Shopping list: buy " + c.ingredient());
        });
        pantry.use("cheese", 4);
        menu.close(); // unsubscribe
        pantry.restock("cheese", 10);
    }
}
pantry.go
package main

import (
	"fmt"
	"sync"
)

type StockChange struct {
	Ingredient        string
	Previous, Current int
}

type Pantry struct {
	mu        sync.Mutex
	stock     map[string]int
	listeners map[*func(StockChange)]struct{} // notification order is not guaranteed
}

func NewPantry() *Pantry {
	return &Pantry{stock: map[string]int{"cheese": 4, "potatoes": 20}, listeners: map[*func(StockChange)]struct{}{}}
}

// Subscribe registers a listener and returns a function that removes it.
func (p *Pantry) Subscribe(fn func(StockChange)) (unsubscribe func()) {
	key := &fn // a unique key for this subscription
	p.mu.Lock()
	defer p.mu.Unlock()
	p.listeners[key] = struct{}{}
	return func() {
		p.mu.Lock()
		defer p.mu.Unlock()
		delete(p.listeners, key)
	}
}

func (p *Pantry) Use(ingredient string, amount int) { p.add(ingredient, -amount) }

func (p *Pantry) Restock(ingredient string, amount int) { p.add(ingredient, amount) }

func (p *Pantry) add(ingredient string, delta int) {
	p.mu.Lock()
	change := StockChange{ingredient, p.stock[ingredient], p.stock[ingredient] + delta}
	p.stock[ingredient] = change.Current
	fns := make([]func(StockChange), 0, len(p.listeners))
	for fn := range p.listeners {
		fns = append(fns, *fn)
	}
	p.mu.Unlock() // notify outside the lock, so listeners may call back into the pantry
	for _, fn := range fns {
		fn(change)
	}
}

func main() {
	pantry := NewPantry()
	stopMenu := pantry.Subscribe(func(c StockChange) {
		if c.Current == 0 {
			fmt.Println("Menu: hiding dishes with", c.Ingredient)
		}
	})
	pantry.Subscribe(func(c StockChange) {
		if c.Current < 3 {
			fmt.Println("Shopping list: buy", c.Ingredient)
		}
	})
	pantry.Use("cheese", 4)
	stopMenu()
	pantry.Restock("cheese", 10)
}
pantry.py
from dataclasses import dataclass
from typing import Callable


@dataclass(frozen=True)
class StockChange:
    ingredient: str
    previous: int
    current: int


Listener = Callable[[StockChange], None]


class Pantry:
    def __init__(self) -> None:
        self._stock = {"cheese": 4, "potatoes": 20}
        self._listeners: list[Listener] = []

    def subscribe(self, listener: Listener) -> Callable[[], None]:
        """Registers a listener and returns a function that unsubscribes it."""
        self._listeners.append(listener)
        return lambda: self._listeners.remove(listener)

    def use(self, ingredient: str, amount: int) -> None:
        self._set(ingredient, self._stock.get(ingredient, 0) - amount)

    def restock(self, ingredient: str, amount: int) -> None:
        self._set(ingredient, self._stock.get(ingredient, 0) + amount)

    def _set(self, ingredient: str, current: int) -> None:
        previous = self._stock.get(ingredient, 0)
        if previous == current:
            return
        self._stock[ingredient] = current
        change = StockChange(ingredient, previous, current)
        for listener in list(self._listeners):  # copy: listeners may unsubscribe
            listener(change)


def menu_board(change: StockChange) -> None:
    if change.current == 0:
        print(f"Menu: hiding dishes with {change.ingredient}")
    elif change.previous == 0:
        print(f"Menu: dishes with {change.ingredient} are back")


def shopping_list(change: StockChange) -> None:
    if change.current < 3:
        print(f"Shopping list: buy {change.ingredient}")


pantry = Pantry()
stop_menu = pantry.subscribe(menu_board)
pantry.subscribe(shopping_list)
pantry.use("cheese", 4)
stop_menu()
pantry.restock("cheese", 10)

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Push or pull?
  • Pitfalls the diagrams keep quiet about
  • A short history of Observer
  • Observer vs Publish/Subscribe
  • When to use it and when not to
  • Related patterns
  • In practice
  • Test yourself
  • Exercise

Create a free account · Sign in