Programming Search⌘K

Patterncore

Observer pattern

Also called Observer, dependents, listener pattern.

A subject keeps a list of observers and calls each of them when its state changes. The subject knows only a small callback interface, not the types of its observers.

Family
behavioral-design
Intent
When one object changes, tell any number of other objects about the change, and keep the changed object free of their concrete types.
Also called
dependents, publish-subscribe (loosely), listener
Refactorings
Replace hard coded notifications with observer

Intent

When one object changes, tell any number of other objects about the change. The changed object knows only a small callback interface. It does not know the concrete types of the objects that react.1

Problem

A program often has one object whose state many other parts of the program follow. A temperature sensor gets a reading. A screen must show the value, an alarm must check a limit, and a log must store it. The number of these parts is not fixed: the user opens and closes windows, and a plugin can add a part at run time.

The direct design calls each part from the sensor: screen.show(value), alarm.check(value), log.write(value). The sensor then depends on the screen, the alarm and the log. Each added part needs a change to the sensor and a rebuild of it. The sensor cannot go into a library, because the library would need to know the types of its users. A test of the sensor must build a screen.

The forces are these. The source of the change must stay independent of the code that reacts. The set of parts that react must change at run time. Each part must see a consistent state when it reacts.

Solution

The sensor becomes a subject. It keeps a list of observers. An observer is any object (or function) that has one operation, often called update or notify. The subject has three operations: subscribe (also called attach or add listener), unsubscribe (detach, remove listener), and an internal notify that calls update on each observer in the list.1

 Subject                         Observer (interface)
 -------------------------       --------------------
 observers: list of Observer --> update(value)
 subscribe(o)                          ^
 unsubscribe(o)                        |
 set(value): store, then         +-----+------+
   for each o: o.update(value)   |            |
                              Display       Alarm

The participants are the subject, the observer interface, and the concrete observers. The subject depends on the interface only. The concrete observers depend on the subject, because they subscribe to it and may read it. So the dependency points from the many to the one, and the one stays reusable.

The sequence of one change is short. A client calls set on the subject. The subject stores the value, so that its state is consistent before anyone looks at it. Then it calls update on each observer in turn. An observer may call back into the subject to read more state. When the last observer returns, set returns to the client.

Push and pull. In the push model the subject sends the changed data with the call: update(21.5). In the pull model the subject sends only "I changed", often with a reference to itself, and each observer reads what it needs: update(sensor), then sensor.value.1 Push is cheaper when every observer needs the same data. Pull keeps the interface stable when observers need different parts of a large state, but each observer must then know the interface of the subject. Many event systems mix the two: the event object carries a small payload and a reference to the source (sender in .NET, event.target in the DOM).

Synchronous and asynchronous notification. In the classic form, notify calls each observer in turn on the same thread, and set returns only after the last observer returns. DOM dispatchEvent, Node.js EventEmitter.emit, C# events and PropertyChangeSupport all work this way.456 In the asynchronous form, the subject puts the change in a queue or a channel, and the observer handles it later or on another thread. The subject then does not wait for slow observers. But an observer can see a value after the subject has changed again, and the program must decide what happens when a queue fills up.

Example

The example files show one program in each language. A sensor has two observers: a display that prints each reading, and an alarm that prints a warning above 30. The program sends 21.5 and 30.5, removes the display, and sends 31.0. Each language uses its own usual form:

Language Form
Python a list of callables, iterated as a copy
JavaScript EventTarget with addEventListener, removal through an AbortSignal
TypeScript a generic subject that returns a Disposable, removed by using
Java java.beans.PropertyChangeSupport with lambdas as PropertyChangeListener
Kotlin Delegates.observable and a list of function values
C# an event of type EventHandler<double> with += and -=
Go one buffered channel for each subscriber, read by a goroutine
Rust a list of Weak<dyn Observer> trait objects
C an array of function pointers, each with a void * context
C++ std::function slots and a move-only subscription that disconnects in its destructor
PowerShell a list of script blocks
Bash an array of function names
SQL triggers on the table that holds the reading
PythonGitHub
from typing import Callable

Observer = Callable[[float], None]


class Sensor:
    def __init__(self) -> None:
        self._observers: list[Observer] = []

    def subscribe(self, observer: Observer) -> Callable[[], None]:
        self._observers.append(observer)
        return lambda: self._observers.remove(observer)

    def set(self, value: float) -> None:
        # A copy, so an observer can unsubscribe while the loop runs.
        for observer in list(self._observers):
            observer(value)


def display(value: float) -> None:
    print(f"display: {value:.1f}")


def alarm(value: float) -> None:
    if value > 30:
        print(f"alarm: {value:.1f} is above 30")


sensor = Sensor()
remove_display = sensor.subscribe(display)
sensor.subscribe(alarm)
sensor.set(21.5)
sensor.set(30.5)
remove_display()
sensor.set(31.0)
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: idiom. Python has no observer construct. A list of callables is the usual form, because functions, bound methods and objects with __call__ are all callables.
  • subscribe returns a function that removes the observer. The caller keeps it in place of a reference to the observer.
  • The loop runs over list(self._observers), a copy, so an observer can remove itself during a notification (see Consequences).
  • weakref.WeakMethod holds a bound method without keeping its object alive, for subjects that must not keep their observers alive.
#include <cstdio>
#include <functional>
#include <map>
#include <utility>

class Sensor {
public:
    using Slot = std::function<void(double)>;

    // Ends the subscription when it goes out of scope.
    class Subscription {
    public:
        Subscription(Sensor* sensor, int id) : sensor_(sensor), id_(id) {}
        Subscription(Subscription&& other) noexcept
            : sensor_(std::exchange(other.sensor_, nullptr)), id_(other.id_) {}
        Subscription(const Subscription&) = delete;
        Subscription& operator=(const Subscription&) = delete;
        Subscription& operator=(Subscription&&) = delete;
        ~Subscription() {
            if (sensor_ != nullptr) {
                sensor_->slots_.erase(id_);
            }
        }

    private:
        Sensor* sensor_;
        int id_;
    };

    [[nodiscard]] Subscription subscribe(Slot slot) {
        int id = next_id_++;
        slots_.emplace(id, std::move(slot));
        return Subscription(this, id);
    }

    void set(double value) {
        auto copy = slots_;  // a slot can unsubscribe during the loop
        for (auto& [id, slot] : copy) {
            slot(value);
        }
    }

private:
    std::map<int, Slot> slots_;
    int next_id_ = 0;
};

int main() {
    Sensor sensor;
    auto alarm = sensor.subscribe([](double value) {
        if (value > 30) {
            std::printf("alarm: %.1f is above 30\n", value);
        }
    });
    {
        auto display = sensor.subscribe([](double value) { std::printf("display: %.1f\n", value); });
        sensor.set(21.5);
        sensor.set(30.5);
    }
    sensor.set(31.0);
}
Output
display: 21.5
alarm: 30.5 is above 30
display: 30.5
alarm: 31.0 is above 30
  • Verdict: idiom. The C++ standard library has no observer or signal type. A container of std::function slots is the usual hand-written form. Libraries such as Boost.Signals2 and Qt signals and slots add thread safety and automatic disconnection.
  • subscribe returns a move-only Subscription. Its destructor removes the slot, so the display stops at the end of its block. This ties the life of the subscription to a scope, as RAII does for memory and files.
  • The keys of the std::map grow with each subscription, so the slots run in the order of subscription. Here the alarm subscribed first, so its line comes first.
  • The subject must outlive each Subscription, because the destructor uses the pointer to the sensor. A subject that can die first needs shared ownership, for example a std::weak_ptr in the subscription.
JavaGitHub
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class Main {
    static class Sensor {
        private final PropertyChangeSupport support = new PropertyChangeSupport(this);
        private double value;

        void subscribe(PropertyChangeListener listener) {
            support.addPropertyChangeListener("value", listener);
        }

        void unsubscribe(PropertyChangeListener listener) {
            support.removePropertyChangeListener("value", listener);
        }

        void set(double next) {
            double old = value;
            value = next;
            support.firePropertyChange("value", old, next);
        }
    }

    public static void main(String[] args) {
        Sensor sensor = new Sensor();
        PropertyChangeListener display =
                event -> System.out.printf("display: %.1f%n", (Double) event.getNewValue());
        PropertyChangeListener alarm = event -> {
            double value = (Double) event.getNewValue();
            if (value > 30) {
                System.out.printf("alarm: %.1f is above 30%n", value);
            }
        };
        sensor.subscribe(display);
        sensor.subscribe(alarm);
        sensor.set(21.5);
        sensor.set(30.5);
        sensor.unsubscribe(display);
        sensor.set(31.0);
        sensor.set(31.0);
    }
}
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: stdlib. java.beans.PropertyChangeSupport keeps the listeners and fires a PropertyChangeEvent that carries the property name, the old value and the changed value. It is in the java.desktop module.
  • PropertyChangeListener has one method, so a lambda can be a listener. Removal needs the same listener object, so the program keeps it in a variable.
  • The last call set(31.0) prints nothing. firePropertyChange fires no event when the old and the changed values are equal and not null.
  • java.util.Observable and java.util.Observer are deprecated. java.util.concurrent.Flow holds the interfaces of reactive streams for asynchronous notification.
#include <stdio.h>

typedef void (*callback)(void *context, double value);

struct observer {
    callback fn;
    void *context;
};

enum { MAX_OBSERVERS = 8 };

struct sensor {
    struct observer observers[MAX_OBSERVERS];
    int count;
};

static int subscribe(struct sensor *s, callback fn, void *context) {
    if (s->count == MAX_OBSERVERS) {
        return -1;
    }
    s->observers[s->count++] = (struct observer){fn, context};
    return 0;
}

static void unsubscribe(struct sensor *s, callback fn, void *context) {
    for (int i = 0; i < s->count; i++) {
        if (s->observers[i].fn == fn && s->observers[i].context == context) {
            s->observers[i] = s->observers[--s->count];
            return;
        }
    }
}

static void set(struct sensor *s, double value) {
    for (int i = 0; i < s->count; i++) {
        s->observers[i].fn(s->observers[i].context, value);
    }
}

static void display(void *context, double value) {
    (void)context;
    printf("display: %.1f\n", value);
}

static void alarm(void *context, double value) {
    const double *limit = context;
    if (value > *limit) {
        printf("alarm: %.1f is above %.0f\n", value, *limit);
    }
}

int main(void) {
    struct sensor sensor = {0};
    double limit = 30;
    subscribe(&sensor, display, NULL);
    subscribe(&sensor, alarm, &limit);
    set(&sensor, 21.5);
    set(&sensor, 30.5);
    unsubscribe(&sensor, display, NULL);
    set(&sensor, 31.0);
    return 0;
}
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: idiom. C has no closures, so an observer is a function pointer and a void * context that holds its state. The alarm gets its limit through the context.
  • The subject stores the observers in a fixed array, so it needs no allocation. subscribe reports a full array with -1.
  • unsubscribe moves the last observer into the free slot. This is cheap, but it changes the order of notification. An observer that unsubscribes itself during set would also make the loop skip the observer that moved.
  • The subject does not own the context. The caller must keep it valid until it unsubscribes.
var sensor = new Sensor();
EventHandler<double> display = (sender, value) => Console.WriteLine($"display: {value:F1}");
sensor.Reading += display;
sensor.Reading += (sender, value) =>
{
    if (value > 30)
    {
        Console.WriteLine($"alarm: {value:F1} is above 30");
    }
};

sensor.Set(21.5);
sensor.Set(30.5);
sensor.Reading -= display;
sensor.Set(31.0);

class Sensor
{
    public event EventHandler<double>? Reading;

    public void Set(double value) => Reading?.Invoke(this, value);
}
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: native. An event member is a delegate field that other classes can only add to (+=) and remove from (-=). Only the declaring class can raise it.
  • A delegate is immutable. += makes a combined delegate with a longer invocation list. A raise calls the methods of the list in order, on the calling thread.
  • Reading?.Invoke reads the field once. A handler that unsubscribes during the raise does not change the list that this raise calls.
  • -= needs the same delegate, so the program keeps the display handler in a variable. A lambda written a second time is a different delegate, and -= with it removes nothing.
  • IObservable<T> and IObserver<T> in the System namespace are the push-based stream form, which the Reactive Extensions library builds on.
JavaScriptGitHub
class Sensor extends EventTarget {
  set(value) {
    this.dispatchEvent(new CustomEvent("reading", { detail: value }));
  }
}

const sensor = new Sensor();
const displayScope = new AbortController();

sensor.addEventListener(
  "reading",
  (event) => console.log(`display: ${event.detail.toFixed(1)}`),
  { signal: displayScope.signal },
);
sensor.addEventListener("reading", (event) => {
  if (event.detail > 30) {
    console.log(`alarm: ${event.detail.toFixed(1)} is above 30`);
  }
});

sensor.set(21.5);
sensor.set(30.5);
displayScope.abort();
sensor.set(31.0);
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: stdlib. EventTarget is part of the DOM Standard, and Node.js has the same class as a global. A class that extends it gets addEventListener, removeEventListener and dispatchEvent.
  • dispatchEvent is synchronous. It calls the listeners in the order of registration and returns after the last one.
  • The signal option removes the listener when the AbortController aborts. One controller can remove many listeners at once, and the code does not need to keep a reference to each listener function.
  • Node.js also has EventEmitter in node:events, with on, off and emit. Its listeners get the arguments of emit directly, with no event object.
TypeScriptGitHub
type Observer<T> = (value: T) => void;

class Subject<T> {
  #observers = new Set<Observer<T>>();

  subscribe(observer: Observer<T>): Disposable {
    this.#observers.add(observer);
    return { [Symbol.dispose]: () => this.#observers.delete(observer) };
  }

  notify(value: T): void {
    for (const observer of [...this.#observers]) {
      observer(value);
    }
  }
}

const sensor = new Subject<number>();
sensor.subscribe((value) => {
  if (value > 30) {
    console.log(`alarm: ${value.toFixed(1)} is above 30`);
  }
});

{
  using display = sensor.subscribe((value) => {
    console.log(`display: ${value.toFixed(1)}`);
  });
  sensor.notify(21.5);
  sensor.notify(30.5);
}
sensor.notify(31.0);
Output
display: 21.5
alarm: 30.5 is above 30
display: 30.5
alarm: 31.0 is above 30
  • Verdict: stdlib. The type checker adds generic observer types to the JavaScript forms: EventTarget, EventEmitter or a hand-written subject such as this one.
  • subscribe returns a Disposable. The using declaration calls its [Symbol.dispose] method when the block ends, so the display is removed at the closing brace, even when the block throws.
  • The observers live in a Set, so the same function cannot subscribe twice. A Set keeps the order of insertion, so the order of notification is the order of subscription.
  • The loop runs over a copy of the set, so an observer can unsubscribe during a notification.
package main

import (
	"fmt"
	"sync"
)

type Sensor struct {
	mu          sync.Mutex
	subscribers map[int]chan float64
	next        int
}

// Subscribe returns a channel of readings and a function that ends the subscription.
func (s *Sensor) Subscribe() (<-chan float64, func()) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.subscribers == nil {
		s.subscribers = map[int]chan float64{}
	}
	id := s.next
	s.next++
	ch := make(chan float64, 8)
	s.subscribers[id] = ch
	return ch, func() {
		s.mu.Lock()
		defer s.mu.Unlock()
		delete(s.subscribers, id)
		close(ch)
	}
}

func (s *Sensor) Set(value float64) {
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, ch := range s.subscribers {
		ch <- value
	}
}

func main() {
	var sensor Sensor
	var wg sync.WaitGroup
	display, stopDisplay := sensor.Subscribe()
	alarm, stopAlarm := sensor.Subscribe()
	wg.Add(2)
	go func() {
		defer wg.Done()
		for value := range display {
			fmt.Printf("display: %.1f\n", value)
		}
	}()
	go func() {
		defer wg.Done()
		for value := range alarm {
			if value > 30 {
				fmt.Printf("alarm: %.1f is above 30\n", value)
			}
		}
	}()
	sensor.Set(21.5)
	sensor.Set(30.5)
	stopDisplay()
	sensor.Set(31.0)
	stopAlarm()
	wg.Wait()
}
Output
alarm: 30.5 is above 30
alarm: 31.0 is above 30
display: 21.5
display: 30.5
  • Verdict: idiom. Go has no observer type in the standard library. A channel for each subscriber is the usual form, and a slice of func(float64) is the usual synchronous form.
  • Each subscriber reads its channel on its own goroutine. The two goroutines run at the same time, so the lines of the display and the lines of the alarm can interleave in any order. The output block compares the lines as a set.
  • The channel has a buffer of 8. When a buffer is full, Set blocks while it holds the lock, so a slow subscriber slows the subject. A subject that must not block drops the value or uses a select with a default case.
  • The function from Subscribe closes the channel, so the for range loop of the subscriber ends. The sync.WaitGroup lets main wait until both loops have ended.
RustGitHub
use std::cell::RefCell;
use std::rc::{Rc, Weak};

trait Observer {
    fn update(&self, value: f64);
}

#[derive(Default)]
struct Sensor {
    observers: RefCell<Vec<Weak<dyn Observer>>>,
}

impl Sensor {
    fn subscribe(&self, observer: &Rc<dyn Observer>) {
        self.observers.borrow_mut().push(Rc::downgrade(observer));
    }

    fn set(&self, value: f64) {
        // Upgrade the live observers first, and drop the dead entries.
        let live: Vec<Rc<dyn Observer>> = {
            let mut observers = self.observers.borrow_mut();
            observers.retain(|weak| weak.strong_count() > 0);
            observers.iter().filter_map(Weak::upgrade).collect()
        };
        for observer in live {
            observer.update(value);
        }
    }

    fn count(&self) -> usize {
        self.observers.borrow().len()
    }
}

struct Display;
struct Alarm;

impl Observer for Display {
    fn update(&self, value: f64) {
        println!("display: {value:.1}");
    }
}

impl Observer for Alarm {
    fn update(&self, value: f64) {
        if value > 30.0 {
            println!("alarm: {value:.1} is above 30");
        }
    }
}

fn main() {
    let sensor = Sensor::default();
    let display: Rc<dyn Observer> = Rc::new(Display);
    let alarm: Rc<dyn Observer> = Rc::new(Alarm);
    sensor.subscribe(&display);
    sensor.subscribe(&alarm);
    sensor.set(21.5);
    sensor.set(30.5);
    drop(display);
    sensor.set(31.0);
    println!("observers: {}", sensor.count());
}
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
observers: 1
  • Verdict: idiom. Rust has no observer type in the standard library. A list of trait objects or of boxed closures is the usual form.
  • The subject holds Weak pointers, so it does not keep its observers alive. drop(display) frees the display, and the next set removes its dead entry. This is the subscription model of the example: an observer lives as long as its owner keeps the Rc.
  • set copies the live observers out of the RefCell before it calls them. If it held the borrow during the calls, an observer that subscribes during a notification would make borrow_mut panic at run time.
  • Threads need Arc, Mutex and Send observers in place of Rc and RefCell. Channels from std::sync::mpsc give the asynchronous form.
KotlinGitHub
import kotlin.properties.Delegates

class Sensor {
    private val observers = mutableListOf<(Double) -> Unit>()

    var value: Double by Delegates.observable(0.0) { _, _, new ->
        for (observer in observers.toList()) {
            observer(new)
        }
    }

    fun subscribe(observer: (Double) -> Unit): () -> Unit {
        observers += observer
        return { observers -= observer }
    }
}

fun main() {
    val sensor = Sensor()
    val removeDisplay = sensor.subscribe { println("display: %.1f".format(it)) }
    sensor.subscribe { if (it > 30) println("alarm: %.1f is above 30".format(it)) }
    sensor.value = 21.5
    sensor.value = 30.5
    removeDisplay()
    sensor.value = 31.0
}
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: stdlib. Delegates.observable in kotlin.properties calls a function after each assignment to a property, with the property, the old value and the assigned value.
  • The delegate has one callback. The list of observers is a list of function values, as in Python.
  • subscribe returns a function that removes the observer, and the loop runs over a copy of the list.
  • SharedFlow and StateFlow from the kotlinx.coroutines library are the asynchronous form. They are not part of the Kotlin standard library.
CREATE TABLE sensor (id INTEGER PRIMARY KEY, value REAL);
CREATE TABLE screen (line TEXT);
CREATE TABLE alarms (line TEXT);
INSERT INTO sensor VALUES (1, 0);

CREATE TRIGGER display AFTER UPDATE OF value ON sensor
BEGIN
    INSERT INTO screen VALUES (printf('display: %.1f', NEW.value));
END;

CREATE TRIGGER alarm AFTER UPDATE OF value ON sensor WHEN NEW.value > 30
BEGIN
    INSERT INTO alarms VALUES (printf('alarm: %.1f is above 30', NEW.value));
END;

UPDATE sensor SET value = 21.5 WHERE id = 1;
UPDATE sensor SET value = 30.5 WHERE id = 1;
DROP TRIGGER display;
UPDATE sensor SET value = 31.0 WHERE id = 1;

SELECT line FROM screen;
SELECT line FROM alarms;
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: idiom. A trigger runs its statements when a row of its table changes. The table is the subject, CREATE TRIGGER subscribes, and DROP TRIGGER unsubscribes.
  • A trigger can only run SQL. It records the change in other tables, and a client reads them later. The example runs in SQLite.
  • PostgreSQL has LISTEN and NOTIFY, which send a message to the connected clients that listen on a channel, when the transaction commits.
BashGitHub
observers=()

subscribe() { observers+=("$1"); }

unsubscribe() {
    local kept=() name
    for name in "${observers[@]}"; do
        [[ $name == "$1" ]] || kept+=("$name")
    done
    observers=("${kept[@]}")
}

set_reading() {
    local observer
    for observer in "${observers[@]}"; do
        "$observer" "$1"
    done
}

display() { echo "display: $1"; }

alarm() {
    if (( $(echo "$1 > 30" | bc) )); then
        echo "alarm: $1 is above 30"
    fi
}

subscribe display
subscribe alarm
set_reading 21.5
set_reading 30.5
unsubscribe display
set_reading 31.0
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: idiom. Bash functions are not values, but a function can be called by its name. An array of function names is the observer list.
  • Bash arithmetic has integers only, so the alarm compares the decimal reading with bc.
  • The expansion "${observers[@]}" in set_reading is made before the loop starts, so an observer that unsubscribes during the loop does not change the current pass.
PowerShellGitHub
class Sensor {
    hidden [System.Collections.Generic.List[scriptblock]] $Observers = [System.Collections.Generic.List[scriptblock]]::new()

    [scriptblock] Subscribe([scriptblock] $observer) {
        $this.Observers.Add($observer)
        $list = $this.Observers
        return { $list.Remove($observer) | Out-Null }.GetNewClosure()
    }

    [void] Set([double] $value) {
        foreach ($observer in @($this.Observers)) {
            & $observer $value
        }
    }
}

$sensor = [Sensor]::new()
$removeDisplay = $sensor.Subscribe({ param($value) Write-Host ('display: {0:F1}' -f $value) })
$null = $sensor.Subscribe({
    param($value)
    if ($value -gt 30) { Write-Host ('alarm: {0:F1} is above 30' -f $value) }
})
$sensor.Set(21.5)
$sensor.Set(30.5)
& $removeDisplay
$sensor.Set(31.0)
Output
display: 21.5
display: 30.5
alarm: 30.5 is above 30
alarm: 31.0 is above 30
  • Verdict: idiom. A list of script blocks is the observer list, and & calls each one.
  • Output from a method of a class does not go to the pipeline, so the observers write with Write-Host.
  • GetNewClosure() makes the removal script block keep the list and the observer after Subscribe returns.
  • Register-ObjectEvent subscribes to the events of a .NET object. PowerShell puts each event in a queue, and the action runs when the session handles the queue, not inside the raise.

Consequences

The subject and the observers are loosely coupled. The subject can live in a lower layer or a library, and it works with observers written later. Observers can be added and removed at run time. One change reaches any number of receivers with one call.12

The costs come from the indirection. A reader of set cannot see which code runs next, and a debugger shows a call through a list. Design Patterns calls this the risk of unexpected updates: an operation on the subject that looks harmless can start a long chain of updates in the observers.1 Each implementation must also decide the five questions below.

The lapsed listener. The subject holds a reference to each observer. In a language with a garbage collector, that reference keeps the observer reachable. When the program closes a window but does not unsubscribe it, the window stays in memory and still gets updates. Kerievsky lists this memory leak as a liability of the pattern, and Microsoft documents the weak event pattern of WPF for the same reason.28 The fixes are: unsubscribe in the close or dispose step of the observer, tie the subscription to a scope (the using block in the TypeScript example, the destructor in the C++ example, the AbortSignal in the JavaScript example), or let the subject hold weak references (weakref.WeakMethod in Python, Weak<T> in Rust).1112 Weak references have a cost: a lambda or a bound method that nothing else holds disappears at once, so the observer stops with no error.

This code runs but gives a wrong answer on purpose.

import weakref


class Sensor:
    def __init__(self):
        self.strong = []
        self.weak = []

    def subscribe(self, method):
        self.strong.append(method)

    def subscribe_weak(self, method):
        self.weak.append(weakref.WeakMethod(method))

    def set(self, value):
        self.weak = [ref for ref in self.weak if ref() is not None]
        for method in self.strong + [ref() for ref in self.weak]:
            method(value)


class Window:
    def __init__(self, name):
        self.name = name

    def on_reading(self, value):
        print(f"{self.name} got {value}")


sensor = Sensor()
first = Window("first")
second = Window("second")
sensor.subscribe(first.on_reading)
sensor.subscribe_weak(second.on_reading)
del first, second  # the program closes both windows
sensor.set(1)
print(f"strong: {len(sensor.strong)}, weak: {len(sensor.weak)}")
Output
first got 1
strong: 1, weak: 0

The program deletes its last name for both windows. The first window still gets the reading, because the bound method in the strong list holds it. The weak entry for the second window is dead, so the subject drops it. CPython frees the second window at once because it counts references. A tracing collector frees it at a later collection.

The order of notification. Most implementations call observers in the order of subscription. The DOM Standard keeps the listeners of a target in an ordered list, Node.js documents that EventEmitter calls its listeners in the order of registration, and a C# delegate calls its invocation list in order.456 Other implementations do not promise an order. The deprecation note of java.util.Observable names its unspecified order of notification as one of the reasons to stop using the class.10 Code that needs the display to update before the log writes depends on an accident unless the subject documents the order. Make each observer independent of the others, or make the order an explicit part of the contract of the subject.

Re-entrancy. An observer can call back into the subject while the subject is notifying. It can unsubscribe itself, subscribe another observer, or change the state of the subject. If the subject iterates over its live list, a removal moves the next observer into the current index, and the loop skips it:

This code runs but gives a wrong answer on purpose.

class Subject:
    def __init__(self):
        self.observers = []

    def notify(self, value):
        for observer in self.observers:  # iterates the live list
            observer(self, value)


def once(subject, value):
    print(f"once: {value}")
    subject.observers.remove(once)


def logger(subject, value):
    print(f"logger: {value}")


subject = Subject()
subject.observers += [once, logger]
subject.notify(1)
subject.notify(2)
Output
once: 1
logger: 2

The logger missed the value 1. The fix is to iterate over a snapshot. The DOM Standard does this: it clones the listener list before it calls the listeners, so a listener added during a dispatch does not run in that dispatch. A removed listener gets a removed flag, and the loop skips it.4 Node.js EventEmitter gets the same effect with copy on write: while an emit runs, a change to the listener array first makes a copy, and the loop in progress keeps the old array.21

class Subject:
    def __init__(self):
        self.observers = []

    def notify(self, value):
        for observer in list(self.observers):  # iterates a snapshot
            observer(self, value)


def once(subject, value):
    print(f"once: {value}")
    subject.observers.remove(once)


def logger(subject, value):
    print(f"logger: {value}")


subject = Subject()
subject.observers += [once, logger]
subject.notify(1)
subject.notify(2)
Output
once: 1
logger: 1
logger: 2

A snapshot does not solve the other form of re-entrancy. When an observer changes the subject during a notification, the subject starts a nested notification. The observers later in the list see the second value first, and then the first value, which is out of date:

This code runs but gives a wrong answer on purpose.

class Thermostat:
    def __init__(self):
        self.value = 0
        self.observers = []

    def set(self, value):
        self.value = value
        for observer in list(self.observers):
            observer(self, value)


def clamp(thermostat, value):
    if value > 30:
        thermostat.set(30)  # changes the subject during notification


def display(thermostat, value):
    print(f"display: {value} (subject holds {thermostat.value})")


thermostat = Thermostat()
thermostat.observers += [clamp, display]
thermostat.set(35)
Output
display: 30 (subject holds 30)
display: 35 (subject holds 30)

The display ends on 35, but the subject holds 30. The usual fixes are: pull the state instead of trusting the pushed value, queue the nested change until the current notification ends, or move the rule (the clamp) into the subject, so that observers never write to it.

An exception in one observer. In a synchronous loop, an exception from one observer leaves the loop, and the observers after it never run. A C# delegate behaves this way: an exception that the handler does not catch stops the invocation, and the methods later in the invocation list are not called.6 EventEmitter.emit also lets the exception out of the loop.19 The DOM takes the other choice: it reports the exception and goes on with the next listener.4 Node.js does the same for EventTarget, but then raises the error as an uncaught exception on process.nextTick(), which ends the process by default.5 A subject that must reach every observer catches the exception of each observer:

def broken(value):
    raise ValueError(f"cannot handle {value}")


def logger(value):
    print(f"logger: {value}")


def notify(observers, value):
    for observer in list(observers):
        try:
            observer(value)
        except Exception as error:
            print(f"{observer.__name__} failed: {error}")


notify([broken, logger], 7)
Output
broken failed: cannot handle 7
logger: 7

Threads. If one thread subscribes while another notifies, the list needs a lock or a copy-on-write structure. A subject that calls its observers while it holds its own lock can deadlock when an observer calls back into the subject. The Go example holds a lock while it sends on the channels, so a full channel blocks the subject. Each subscriber reads its own channel on its own goroutine.13

When not to use it

Do not use the pattern when there is one receiver that does not change. A direct call is clearer, and the reader can follow it. Kerievsky lists this as a liability: the pattern complicates a design where a hard-coded notification is enough. He also advises to start with the hard-coded notification and to change to an observer when the need is real.2

Do not use it to build a chain of reactions, where one observer updates a second subject, which notifies a third. Such cascades are hard to trace, can loop, and can deliver values out of order, as the thermostat example shows. Kerievsky names cascading notifications as a liability and suggests a mediator for such code.2 A mediator that owns the order of the updates, or a dataflow model with signals, handles chains better.

Do not use it across process or network boundaries in its plain form. A remote observer can fail, be slow or be gone, and a synchronous call to it blocks the subject. Use a message broker with publish-subscribe instead.

An observer list that no one removes entries from becomes the lapsed listener leak. A program with many subjects, where each observer reacts by changing other subjects, has control flow that no one can read from the source code.

Event objects and multicast delegates. C# builds the pattern into the language. An event is a delegate field whose invocation list is the observer list, and only the declaring class can raise it.7 A delegate instance is immutable, so += makes a second, combined delegate, and a raise that has already read the field calls the old list.6 The DOM EventTarget and the Node.js EventEmitter key their observers by an event name, so one subject has many lists.45

Property change events. java.beans.PropertyChangeSupport is a helper that a class holds as a field. It sends an event with the name of the property, the old value and the changed value. It sends nothing when the old and the changed values are equal and not null.920 Kotlin Delegates.observable attaches a callback to one property in the same way.

Publish-subscribe. In publish-subscribe, publishers send messages to a topic or a channel, and subscribers register with the channel, not with the publisher. An intermediary decouples the two sides: an event bus in one process, or a broker such as an MQTT or Kafka server across processes. Eugster and others describe three kinds of decoupling: in space (the two sides do not know each other), in time (they need not be active at the same moment), and in synchronization (the publisher does not block).3 The classic Observer pattern gives only part of the first kind. The subject knows its observers through the interface, and each observer knows the subject. It gives no decoupling in time, because an observer must exist when the subject notifies.

Reactive streams. A stream turns the observer into a subscriber with three callbacks: the next value, an error, and completion. The Reactive Streams specification adds backpressure: the subscriber calls request(n), and the publisher may send at most n items.16 This bounds the queues that asynchronous notification needs. Java java.util.concurrent.Flow holds the same four interfaces (Publisher, Subscriber, Subscription and Processor).17 Kotlin SharedFlow is a hot flow that broadcasts each value to all collectors, and StateFlow keeps one current value and drops a value equal to the previous one.1415 These flows come from the kotlinx.coroutines library, not from the Kotlin standard library, so the Kotlin example uses Delegates.observable instead.

Signals. A signal is a cell that holds one current value and records which computations read it. A computed signal does not subscribe by hand. It reads other signals, and the runtime records those reads as its dependencies. A write marks the dependent computations as stale, and a computed signal runs again only when someone reads it. This pull step avoids the out-of-date values of a push cascade (a "glitch"), at a cost: two writes with no read between them show only the second value. The TC39 proposal for signals in JavaScript is at Stage 1.18

Mediator. A mediator also decouples objects, but it puts the logic of who reacts to what in one place. The Observer pattern spreads that logic over the observers. The two can work together. Design Patterns describes a change manager that sits between subjects and observers and fixes the update order, and it calls this change manager an instance of Mediator.1

Model-view-controller. In MVC, the views observe the model. When the model changes, it tells its dependents, and each view asks the model for the data that it shows.22 Design Patterns names Smalltalk MVC as the first example of Observer.1

Known uses

  • Node.js: EventEmitter.prototype.emit in lib/events.js at v26.8.1 calls the listeners of one event name in order, synchronously, in a loop over the listener array. A counter marks the array while an emit runs, and ensureMutableListenerArray copies it before a change.
  • OpenJDK: firePropertyChange in PropertyChangeSupport.java at jdk-25+36 skips the notification when the old and the changed values are equal and not null. Otherwise it calls each listener in a loop over an array.
  • Smalltalk-80: the dependents mechanism of Object and the model-view-controller framework, as Design Patterns records in the Known Uses section of Observer, and as Krasner and Pope describe for MVC.122

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Observer, page 293 (Also Known As, Consequences, Implementation, Known Uses)
  2. Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 8, Generalization, Replace Hard-Coded Notifications with Observer (motivation, benefits and liabilities)
  3. Eugster, Felber, Guerraoui and Kermarrec, The many faces of publish/subscribe, ACM Computing Surveys 35(2), 2003, Abstract (decoupling in space, time and synchronization)
  4. WHATWG DOM Standard, 2.9 Dispatching events, invoke and inner invoke
  5. Node.js documentation, Events, EventTarget error handling; Asynchronous vs. synchronous
  6. C# language specification, Delegates, 21.5 Delegate instantiation; 21.6 Delegate invocation
  7. C# language specification, Classes, 15.8.2 Field-like events
  8. Weak event patterns (WPF), Microsoft Learn, Why implement the weak event pattern
  9. Java SE 25 API, java.beans.PropertyChangeSupport, class description; firePropertyChange
  10. Java SE 25 API, java.util.Observable, Deprecated note
  11. The Python Standard Library, weakref, Python 3.14, weakref.WeakMethod
  12. Rust standard library, std::rc::Weak, struct description; method upgrade
  13. The Go Programming Language Specification, Channel types; Send statements
  14. kotlinx.coroutines API, SharedFlow, interface description
  15. kotlinx.coroutines API, StateFlow, interface description, conflation
  16. Reactive Streams for the JVM, specification 1.0.4, Goals, Design and Scope; 3. Subscription
  17. JEP 266, More Concurrency Updates, Description, interfaces for reactive streams (java.util.concurrent.Flow)
  18. TC39 proposal, JavaScript Signals standard proposal, README, status (Stage 1)
  19. Node.js v26.8.1 source, lib/events.js, EventEmitter.prototype.emit, lines 489 to 543
  20. OpenJDK jdk-25+36 source, java/beans/PropertyChangeSupport.java, firePropertyChange and fire, lines 324 to 347
  21. Node.js v26.8.1 source, lib/events.js, ensureMutableListenerArray, lines 907 to 914
  22. Krasner and Pope, A cookbook for using the model-view controller user interface paradigm in Smalltalk-80, JOOP 1(3), 1988, the dependency mechanism between a model and its views (changed and update messages)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4ACQHF/text.yaml