Observer Pattern
Notify registered receivers of a change without making the source depend on every receiver.
· Last updated: 2026-11-07 · 16 min read
Overview
A temperature sensor that initially shows its readings on a single display may later need to feed an alarm and a chart as well. If the sensor calls Display.Show() and HeatAlarm.Check() directly, then every added receiver forces a change to the sensor code as well. The sensor ends up owning who reads the value and in what order they get called.
Instead, receivers register in advance the methods they want called. The sensor keeps those registered methods and notifies them whenever a new value arrives, so it needs no code that tells a display from an alarm. The value is what changes; what to do with it is decided on the receiving side. The structure that separates the object announcing a change from the objects subscribing to it is the Observer pattern, and the announcing side is called the subject while the receiving side is called the observer.
UML
The diagram shows how the two roles from the previous section appear as types in code. The announcer is TemperatureSensor, the subscribers are Display and HeatAlarm, and += registers a subscription while -= removes it. The diagram leaves out the 28-degree measurement so that the two later ones stay legible. Both receive 31 degrees; after the alarm subscription is removed, only the display receives 32, and time flows downward.
The types shown in the class diagram are used unchanged in the extended example that follows. TemperaturePanel holds a reference to the sensor and subscribes through it, and it removes the subscription in IDisposable.Dispose(). There is no separate Observer interface that ports the GoF roles by name; C# events and method subscriptions express that relationship instead.
History
Glenn E. Krasner and Stephen T. Pope's 1988 account of Smalltalk-80 MVC describes registering dependents with a model and notifying them when it changes. The model broadcasts a change message without identifying each kind of view. This is a documented use of change notification before the GoF book.1
Gamma, Helm, Johnson and Vlissides cataloged Observer as a behavioral pattern in Design Patterns in 1994. GoF refers to those four authors.2
C# events provide one way to express notifications between objects. The examples below use events; .NET also supplies IObservable<T> and IObserver<T> for modeling subscriptions and notifications.34
Why use it?
The sensor produces the measurements, the display presents them, and the alarm decides whether a threshold is exceeded. Putting all three into one sensor class means touching the measurement code whenever a display is swapped or an alarm is added. If receivers subscribe themselves, the roles stay separate and still receive the same change. All three need that one value and nothing else from one another.
EventHandler<TemperatureChanged> is the type of a method that takes the sending object and a reading as its arguments. One shape like that lets a display method and an alarm method sit in the same list. A delegate is a reference that keeps such a method and can call it, and Changed is the event that subscribes methods of that type. Because the reading arrives as a read-only object, a subscriber never has to query the sensor's mutable state again.
The value rides along inside the notification. A notification could announce only that something changed and leave receivers to read the state themselves, but then what a receiver sees depends on when it reads. This example therefore sends the reading itself. What a notification means and which state it carries still has to be settled first. With a single fixed receiver, calling the method directly may be simpler.
Example
using System;
using System.Globalization;
var sensor = new TemperatureSensor();
var display = new Display();
var alarm = new HeatAlarm();
sensor.Changed += display.Show;
sensor.Changed += alarm.Check;
sensor.Measure(28m);
sensor.Measure(31m);
sensor.Changed -= alarm.Check;
sensor.Measure(32m);
public sealed class TemperatureChanged : EventArgs
{
public decimal Celsius { get; }
public TemperatureChanged(decimal celsius) => Celsius = celsius;
}
// The subject calls registered functions without knowing subscriber types.
public sealed class TemperatureSensor
{
public event EventHandler<TemperatureChanged>? Changed;
public void Measure(decimal celsius) => Changed?.Invoke(this, new TemperatureChanged(celsius));
}
public sealed class Display
{
public void Show(object? sender, TemperatureChanged change) =>
Console.WriteLine("Display: " + change.Celsius.ToString(CultureInfo.InvariantCulture));
}
public sealed class HeatAlarm
{
public void Check(object? sender, TemperatureChanged change)
{
if (change.Celsius >= 30m)
Console.WriteLine("Alarm: " + change.Celsius.ToString(CultureInfo.InvariantCulture));
}
}Display: 28
Display: 31
Alarm: 31
Display: 32The effect of registering and removing a subscription shows up directly in the output. At 28 degrees both methods are still called, but because the reading is below the alarm's 30-degree threshold, only the display prints. Both print at 31, and after the alarm is removed with -=, measuring 32 reaches only the display. Changed?.Invoke(...) means the event is invoked only when subscribers are present.
During notification
Handlers run synchronously in registration order, so a slow handler delays the measurement call. An exception from one handler stops the remaining invocations and reaches the caller; event syntax does not isolate each subscriber's failures. A handler that calls Measure() again can also interleave a new notification with the current one.5
Registering the same method twice makes two calls, and one -= removes one registration. Changing subscriptions during a notification does not change the invocation list already being called; the new list applies to the next notification. A newly created lambda is not a reliable way to remove an earlier registration. Use a named handler or retain the delegate you registered when it must be removed later.6
An extended example
Tying the subscription's lifetime to the object
The extended example starts with what the basic one leaves open: when does a subscription end? If a screen subscribes when it opens, something has to release that subscription when it closes. The publisher's event holds references to a subscriber's method and object, so a long-lived publisher can keep a closed screen alive. That is why TemperaturePanel owns its own subscription and releases it in Dispose().
IDisposable provides the Dispose() cleanup contract; a using block calls that method when the block exits. Here, disposing the panel removes its own event subscription without closing the sensor.7
using System;
using System.Globalization;
var sensor = new TemperatureSensor();
using (var room = new TemperaturePanel(sensor, "Room", Console.WriteLine))
{
sensor.Measure(28m);
using (var chart = new TemperaturePanel(sensor, "Chart", Console.WriteLine))
{
sensor.Measure(31m);
}
sensor.Measure(32m);
room.Dispose();
sensor.Measure(33m);
}
sensor.Measure(34m);
public sealed class TemperatureChanged : EventArgs
{
public decimal Celsius { get; }
public TemperatureChanged(decimal celsius) => Celsius = celsius;
}
// The subject calls registered functions without knowing subscriber types.
public sealed class TemperatureSensor
{
public event EventHandler<TemperatureChanged>? Changed;
public void Measure(decimal celsius) => Changed?.Invoke(this, new TemperatureChanged(celsius));
}
// The subscriber keeps the publisher and unsubscribes its handler method at the end of its lifetime.
public sealed class TemperaturePanel : IDisposable
{
private readonly TemperatureSensor sensor;
private readonly string name;
private readonly Action<string> write;
private bool disposed;
public TemperaturePanel(TemperatureSensor sensor, string name, Action<string> write)
{
this.sensor = sensor;
this.name = name;
this.write = write;
sensor.Changed += Show;
}
private void Show(object? sender, TemperatureChanged change)
{
if (disposed)
return;
write(name + ": " + change.Celsius.ToString(CultureInfo.InvariantCulture));
}
public void Dispose()
{
if (disposed)
return;
disposed = true;
sensor.Changed -= Show;
}
}Room: 28
Room: 31
Chart: 31
Room: 32The output follows each unsubscribe point. Chart leaves its inner using block and unsubscribes before the 32-degree reading. Calling room.Dispose() prevents it from processing 33. The later cleanup at the end of its block is harmless because the disposed guard handles repeated calls. Measuring 34 after all panels have left produces no output.
Stopping work and handling concurrency
Even with the lifetime handled, a list being walked can still hold a subscriber that is already disposed. The guard in Show() prevents this panel from processing a reading after disposal. On one thread, an earlier handler can dispose the panel while its callback remains in the current invocation list; the guard stops that callback from processing the reading. It does not cancel work already executing.
The example also assumes a single thread. Measuring and unsubscribing on several threads at once is outside the scope of this example. Such a case needs its own decisions about how callback execution and shutdown are synchronized and how work is dispatched to a UI thread. Event syntax alone also does not fix the order of overlapping notifications or whether the same event is handled twice.
These notifications travel only through one process's memory, so sending them to another process or keeping them across a restart needs a transport and a storage policy. Calling a failed subscriber again also requires deciding how to prevent duplicate work, and an Observer example should not be expected to offer the delivery guarantees of a message queue.
TypeScript example
The roles split the same way in the TypeScript version. The sensor produces the readings, and subscribers own the reactions, whether that is a display or an alarm. Putting a subscription list between the two means that adding receivers requires no per-receiver branches in the measurement code.
type TemperatureChanged = Readonly<{ celsius: number }>;
type Observer = (change: TemperatureChanged) => void;
// The subject calls registered functions without knowing subscriber types.
class TemperatureSensor {
private readonly observers = new Map<symbol, Observer>();
subscribe(observer: Observer): () => void {
const key = Symbol();
this.observers.set(key, observer);
return () => { this.observers.delete(key); };
}
measure(celsius: number): void {
const change = Object.freeze({ celsius });
for (const observer of [...this.observers.values()]) observer(change);
}
}
// The subscriber retains its unsubscribe function and calls it at the end of its lifetime.
class TemperaturePanel {
private disposed = false;
private readonly unsubscribe: () => void;
constructor(sensor: TemperatureSensor, name: string, write: (line: string) => void) {
this.unsubscribe = sensor.subscribe(change => {
if (!this.disposed) write(name + ": " + change.celsius);
});
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.unsubscribe();
}
}
const sensor = new TemperatureSensor();
const room = new TemperaturePanel(sensor, "Room", line => console.log(line));
sensor.measure(28);
const chart = new TemperaturePanel(sensor, "Chart", line => console.log(line));
sensor.measure(31);
chart.dispose();
sensor.measure(32);
room.dispose();
room.dispose();
sensor.measure(33);Room: 28
Room: 31
Chart: 31
Room: 32What differs here is how you hold on to the removal. Instead of C# events, each subscription hands back an unsubscribe function. Calls are synchronous and work from the subscription list as it stood when the call began. Registering the same function twice creates two separate subscriptions, so it is called twice, and an exception raised in a subscriber propagates unchanged to the caller.
Problems caused by overuse
One change now turns into work in several places. When subscriptions are scattered across many places, it is hard to follow who runs and in what order once a single value changes. Nothing at the call site hints at that order. A cycle in which a notification changes the same state again, or a subscription that is never released, leads to unintended duplicate execution. Events used without agreed publisher and subscriber lifetimes and a reentrancy policy create hidden coupling stronger than a direct call.
Typing notifications with Subject<T>
T in Subject<T> is the value sent to observers. Subject<double> can carry temperatures and Subject<string> can carry text while reusing the same registration and notification structure. SubscribeObserver and NotifyObservers name the two roles directly.
A subscription is tracked as a registration, not as a bare callback. Each subscription creates its own registration and returns an unsubscribe handle. Registering the same callback twice still creates two registrations; disposing one handle removes only that registration. Notification walks a snapshot taken at the start of the call.
C#
using System;
using System.Collections.Generic;
var subject = new Subject<int>();
using var first = subject.SubscribeObserver(value => Console.WriteLine("A:" + value));
var second = subject.SubscribeObserver(value => Console.WriteLine("B:" + value));
subject.NotifyObservers(3);
second.Dispose();
subject.NotifyObservers(4);
// TYPES
sealed class Subject<T>
{
private readonly List<Subscription> subscriptions = new();
public IDisposable SubscribeObserver(Action<T> receive)
{
var item = new Subscription(this, receive);
subscriptions.Add(item);
return item;
}
public void NotifyObservers(T value)
{
// This notification uses the registrations present at its start.
foreach (var item in subscriptions.ToArray()) item.Receive(value);
}
private sealed class Subscription : IDisposable
{
private Subject<T>? owner;
public Action<T> Receive { get; }
public Subscription(Subject<T> owner, Action<T> receive)
{ this.owner = owner; Receive = receive; }
public void Dispose()
{
owner?.subscriptions.Remove(this);
owner = null;
}
}
}A:3
B:3
A:4TypeScript
class Subject<T> {
private readonly subscriptions = new Set<{ receive: (value: T) => void }>();
subscribeObserver(receive: (value: T) => void): () => void {
const item = { receive };
this.subscriptions.add(item);
return () => { this.subscriptions.delete(item); };
}
notifyObservers(value: T): void {
// Snapshot the registrations for this notification.
for (const item of [...this.subscriptions]) item.receive(value);
}
}
const subject = new Subject<number>();
subject.subscribeObserver(value => console.log("A:" + value));
const unsubscribe = subject.subscribeObserver(value => console.log("B:" + value));
subject.notifyObservers(3);
unsubscribe();
subject.notifyObservers(4);A:3
B:3
A:4Notifications are synchronous here. A callback exception ends the current call and propagates to its caller. The snapshot policy makes subscriptions added or removed during a notification take effect on the next notification; synchronizing concurrent threads is a separate responsibility.
The official references describe the type-parameter syntax and library contracts.8
Push vs. Pull models and the boundary with backpressure
GoF contrasted two ways of delivering state across a notification: the Push model and the Pull model. In the Push model used by our temperature sensor (TemperatureChanged(Celsius)), the subject packages an immutable snapshot into the notification itself; in the Pull model, the subject sends only a bare signal and lets each observer query the subject back for whatever fields it cares about. Pull keeps the event signature tiny, but if the subject mutates again during notification or across threads, late observers end up reading a different state than early ones (see Concurrency Control).
Classic GoF Observer also lacks first-class channels for stream termination and failure. Erik Meijer's formulation of Reactive Extensions (Rx) and .NET's IObservable<T> / IObserver<T> derived OnNext, OnCompleted, and OnError as the exact category-theoretic dual of the Iterator Pattern protocol (next value, end of sequence, thrown exception).9 Even so, pure push notifications give a slow observer no way to slow down a fast producer; once notifications cross asynchronous boundaries, you need explicit Backpressure to bound memory.
Related reading
Footnotes
- Glenn E. Krasner and Stephen T. Pope. A Cookbook for Using the Model-View-Controller User Interface Paradigm in Smalltalk-80, JOOP, August/September 1988, pp. 26-27, Dependents. Original PDF. ↩
- Gamma, Helm, Johnson and Vlissides. Design Patterns (1994), Observer. Publisher record. ↩
- Microsoft. Events. ↩
- Microsoft. Observer design pattern,
IObservable<T>andIObserver<T>in .NET. ↩ - Microsoft. C# language specification, Delegates §21.6. ↩
- Microsoft. Subscribe to and unsubscribe from events. ↩
- Microsoft. IDisposable.Dispose. ↩
- C# generics; TypeScript generics ↩
- Erik Meijer, "Subject/Observer is Dual to Iterator," Communications of the ACM 55(7), 2012, pp. 70–75. DOI. ↩