Observer the Modern Way: Events and Listeners
When every device writes Pass 1's listener list again by hand, and a closed phone screen keeps hearing every change because nothing takes it off the list, it's time for each language's own tools: C#'s event, JavaScript's EventTarget, and a subscribe that hands back a way to unsubscribe.
Journeyman · OOP · Updated
After this lesson you can
- Subscribe and unsubscribe listeners with each language's own tools: events, EventTarget, or an unsubscribe handle
- Spot the smells that point to modern Observer events: hand-written listener lists, and listeners that never unsubscribe
Key takeaways
- Pass 1's Observer was a list of listeners the subject wrote itself; this lesson adds the other half: leaving the list.
- The smell: the same hand-written listener list in every class, and listeners that are never removed, so closed screens keep reacting.
- A listener left on the list after it's done is a lapsed listener: it keeps working for nobody, and keeps its object in memory.
- The modern tools: C#'s event with += and -=, JavaScript's EventTarget with addEventListener and an AbortController, and in Java and Python a subscribe that returns an unsubscribe.
- Unsubscribe with the exact function you subscribed, or the one subscribe handed back; a new copy of it removes nothing.
Before this: Observer: Tell Whoever's Listening (Pass 1), and passing a function as a value.
In Pass 1, the bakery's order desk kept its own list of listeners: anyone could subscribe, and placing an order told each one. One function was enough for a listener. Now that list turns up in the hub, again and again. The front door tells listeners when it locks or unlocks; so do the lights, the alarm and the thermostat, each with its own copy of the same list. And the hub has something the bakery didn't: screens that open and close. Pass 1 said unsubscribing would come later. This is later.
The symptom: a closed screen that still hears everything
Maya's phone app has a front-door screen. When she opens it, it subscribes to the door; when she closes it, it marks itself closed. Watch what happens after she closes it:
FrontDoor door = new FrontDoor();
door.Subscribe(what => Console.WriteLine( quot;Log: {what}"));
DoorScreen doorScreen = new DoorScreen(door);
door.Unlock();
Console.WriteLine("Maya closes the door screen");
doorScreen.Close();
door.Lock();
// Pass 1's listener list, written again by hand.
class FrontDoor
{
private readonly List<Action<string>> listeners = new List<Action<string>>();
public void Subscribe(Action<string> listener) => listeners.Add(listener);
public void Unlock() => Tell("front door unlocked");
public void Lock() => Tell("front door locked");
private void Tell(string what)
{
foreach (Action<string> listener in listeners)
{
listener(what);
}
}
}
// The phone app's screen for the front door.
class DoorScreen
{
private bool isOpen = true;
public DoorScreen(FrontDoor door) { door.Subscribe(Show); }
private void Show(string what) => Console.WriteLine( quot;Door screen{(isOpen ? "" : " (closed!)")}: {what}");
public void Close() => isOpen = false;
}
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
Door screen (closed!): front door locked
// Pass 1's listener list, written again by hand.
class FrontDoor {
private final List<Consumer<String>> listeners = new ArrayList<>();
void subscribe(Consumer<String> listener) { listeners.add(listener); }
void unlock() { tell("front door unlocked"); }
void lock() { tell("front door locked"); }
private void tell(String what) {
for (Consumer<String> listener : listeners) {
listener.accept(what);
}
}
}
// The phone app's screen for the front door.
class DoorScreen {
private boolean isOpen = true;
DoorScreen(FrontDoor door) { door.subscribe(this::show); }
void show(String what) { IO.println("Door screen" + (isOpen ? "" : " (closed!)") + ": " + what); }
void close() { isOpen = false; }
}
void main() {
FrontDoor door = new FrontDoor();
door.subscribe(what -> IO.println("Log: " + what));
DoorScreen doorScreen = new DoorScreen(door);
door.unlock();
IO.println("Maya closes the door screen");
doorScreen.close();
door.lock();
}
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
Door screen (closed!): front door locked
class FrontDoor:
"""Pass 1's listener list, written again by hand."""
def __init__(self):
self.listeners = []
def subscribe(self, listener):
self.listeners.append(listener)
def unlock(self):
self.tell("front door unlocked")
def lock(self):
self.tell("front door locked")
def tell(self, what):
for listener in self.listeners:
listener(what)
class DoorScreen:
"""The phone app's screen for the front door."""
def __init__(self, door):
self.is_open = True
door.subscribe(self.show)
def show(self, what):
print(f"Door screen{'' if self.is_open else ' (closed!)'}: {what}")
def close(self):
self.is_open = False
door = FrontDoor()
door.subscribe(lambda what: print(f"Log: {what}"))
door_screen = DoorScreen(door)
door.unlock()
print("Maya closes the door screen")
door_screen.close()
door.lock()
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
Door screen (closed!): front door locked
// Pass 1's listener list, written again by hand.
class FrontDoor {
#listeners = [];
subscribe(listener) { this.#listeners.push(listener); }
unlock() { this.#tell("front door unlocked"); }
lock() { this.#tell("front door locked"); }
#tell(what) {
for (const listener of this.#listeners) listener(what);
}
}
// The phone app's screen for the front door.
class DoorScreen {
#isOpen = true;
constructor(door) { door.subscribe((what) => this.#show(what)); }
#show(what) { console.log(`Door screen${this.#isOpen ? "" : " (closed!)"}: ${what}`); }
close() { this.#isOpen = false; }
}
const door = new FrontDoor();
door.subscribe((what) => console.log(`Log: ${what}`));
const doorScreen = new DoorScreen(door);
door.unlock();
console.log("Maya closes the door screen");
doorScreen.close();
door.lock();
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
Door screen (closed!): front door locked
type Listener = (what: string) => void;
// Pass 1's listener list, written again by hand.
class FrontDoor {
#listeners: Listener[] = [];
subscribe(listener: Listener): void { this.#listeners.push(listener); }
unlock(): void { this.#tell("front door unlocked"); }
lock(): void { this.#tell("front door locked"); }
#tell(what: string): void {
for (const listener of this.#listeners) listener(what);
}
}
// The phone app's screen for the front door.
class DoorScreen {
#isOpen = true;
constructor(door: FrontDoor) { door.subscribe((what) => this.#show(what)); }
#show(what: string): void { console.log(`Door screen${this.#isOpen ? "" : " (closed!)"}: ${what}`); }
close(): void { this.#isOpen = false; }
}
const door = new FrontDoor();
door.subscribe((what) => console.log(`Log: ${what}`));
const doorScreen = new DoorScreen(door);
door.unlock();
console.log("Maya closes the door screen");
doorScreen.close();
door.lock();
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
Door screen (closed!): front door locked
The last line is the bug: the screen is closed, and it's still reacting. In a real app it would redraw a screen nobody sees, use battery, and stay in memory forever, because the door's list still holds it. Open and close the screen fifty times in a day and the door is telling fifty dead screens about every lock.
- The symptom: the same listener list written by hand in every class that announces changes, with a way in (
subscribe) and no way out; closed screens that keep reacting. - The cause: Pass 1's Observer covered joining the list, and nothing covered leaving it. A listener left behind after it's done is called a lapsed listener.
What would you try?
Have the screen ignore messages once it's closed. That's what isOpen does, and it only hides the problem: the screen still gets every message and still sits in memory.
Clear the whole list now and then. That also throws out the activity log, which never closes.
Copy a better list into every device. Add unsubscribe to the front door, then to the light, the alarm and the thermostat. It works, and it's the same twenty lines in four classes.
What we want is a way out for each listener, and ideally one we don't write again in every class.
The fix: subscribe, and unsubscribe
Think of a group chat for the people in Maya's building. Joining is one tap, and so is leaving: when Sam moves out, he leaves the group, and the messages stop reaching his phone. Nobody has to tell the group to ignore him; he's not in it.
So each listener that joins must have a way to leave, and use it when it's done: unsubscribe when the screen closes. The first fix adds that to Pass 1's list; the modern one lets each language's own tools do the work.

The classic version: Pass 1's list, with a way out
The list gets unsubscribe, and the screen calls it when it closes. One detail matters: the screen must hand back the same function it subscribed, so the list can find it:
FrontDoor door = new FrontDoor();
door.Subscribe(what => Console.WriteLine( quot;Log: {what}"));
DoorScreen doorScreen = new DoorScreen(door);
door.Unlock();
Console.WriteLine("Maya closes the door screen");
doorScreen.Close();
door.Lock();
class FrontDoor
{
private readonly List<Action<string>> listeners = new List<Action<string>>();
public void Subscribe(Action<string> listener) => listeners.Add(listener);
public void Unsubscribe(Action<string> listener) => listeners.Remove(listener);
public void Unlock() => Tell("front door unlocked");
public void Lock() => Tell("front door locked");
private void Tell(string what)
{
foreach (Action<string> listener in listeners)
{
listener(what);
}
}
}
class DoorScreen
{
private readonly FrontDoor door;
public DoorScreen(FrontDoor door) { this.door = door; door.Subscribe(Show); }
private void Show(string what) => Console.WriteLine( quot;Door screen: {what}");
public void Close() => door.Unsubscribe(Show); // leave the list when the screen closes
}
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
class FrontDoor {
private final List<Consumer<String>> listeners = new ArrayList<>();
void subscribe(Consumer<String> listener) { listeners.add(listener); }
void unsubscribe(Consumer<String> listener) { listeners.remove(listener); }
void unlock() { tell("front door unlocked"); }
void lock() { tell("front door locked"); }
private void tell(String what) {
for (Consumer<String> listener : listeners) {
listener.accept(what);
}
}
}
class DoorScreen {
private final FrontDoor door;
private final Consumer<String> listener = this::show; // kept, so the very same one can leave
DoorScreen(FrontDoor door) { this.door = door; door.subscribe(listener); }
void show(String what) { IO.println("Door screen: " + what); }
void close() { door.unsubscribe(listener); } // leave the list when the screen closes
}
void main() {
FrontDoor door = new FrontDoor();
door.subscribe(what -> IO.println("Log: " + what));
DoorScreen doorScreen = new DoorScreen(door);
door.unlock();
IO.println("Maya closes the door screen");
doorScreen.close();
door.lock();
}
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
class FrontDoor:
def __init__(self):
self.listeners = []
def subscribe(self, listener):
self.listeners.append(listener)
def unsubscribe(self, listener):
self.listeners.remove(listener)
def unlock(self):
self.tell("front door unlocked")
def lock(self):
self.tell("front door locked")
def tell(self, what):
for listener in self.listeners:
listener(what)
class DoorScreen:
def __init__(self, door):
self.door = door
door.subscribe(self.show)
def show(self, what):
print(f"Door screen: {what}")
def close(self):
self.door.unsubscribe(self.show) # leave the list when the screen closes
door = FrontDoor()
door.subscribe(lambda what: print(f"Log: {what}"))
door_screen = DoorScreen(door)
door.unlock()
print("Maya closes the door screen")
door_screen.close()
door.lock()
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
class FrontDoor {
#listeners = [];
subscribe(listener) { this.#listeners.push(listener); }
unsubscribe(listener) { this.#listeners = this.#listeners.filter((l) => l !== listener); }
unlock() { this.#tell("front door unlocked"); }
lock() { this.#tell("front door locked"); }
#tell(what) {
for (const listener of this.#listeners) listener(what);
}
}
class DoorScreen {
#door;
#listener = (what) => console.log(`Door screen: ${what}`); // kept, so the very same one can leave
constructor(door) {
this.#door = door;
door.subscribe(this.#listener);
}
close() { this.#door.unsubscribe(this.#listener); } // leave the list when the screen closes
}
const door = new FrontDoor();
door.subscribe((what) => console.log(`Log: ${what}`));
const doorScreen = new DoorScreen(door);
door.unlock();
console.log("Maya closes the door screen");
doorScreen.close();
door.lock();
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
type Listener = (what: string) => void;
class FrontDoor {
#listeners: Listener[] = [];
subscribe(listener: Listener): void { this.#listeners.push(listener); }
unsubscribe(listener: Listener): void { this.#listeners = this.#listeners.filter((l) => l !== listener); }
unlock(): void { this.#tell("front door unlocked"); }
lock(): void { this.#tell("front door locked"); }
#tell(what: string): void {
for (const listener of this.#listeners) listener(what);
}
}
class DoorScreen {
#door: FrontDoor;
#listener: Listener = (what) => console.log(`Door screen: ${what}`); // kept, so the very same one can leave
constructor(door: FrontDoor) {
this.#door = door;
door.subscribe(this.#listener);
}
close(): void { this.#door.unsubscribe(this.#listener); } // leave the list when the screen closes
}
const door = new FrontDoor();
door.subscribe((what) => console.log(`Log: ${what}`));
const doorScreen = new DoorScreen(door);
door.unlock();
console.log("Maya closes the door screen");
doorScreen.close();
door.lock();
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
The closed screen is gone from the list, so the last line is gone too. Notice why Java, JavaScript and TypeScript keep the listener in a field: this::show in Java, and a new arrow function in JavaScript, make a new function object each time they're written, and removing a new one removes nothing. C# and Python compare the method and its object, so Show and self.show find the original.
The modern version: each language's own tools
Writing the list in every class is the part each language has already done for you. C# has the event keyword; JavaScript and TypeScript have EventTarget, the same machine behind a browser button's addEventListener, and an AbortController that removes listeners for you. Java and Python have no built-in event for objects; the modern habit there is that subscribe hands back a small function that unsubscribes, so nobody has to keep the listener around:
FrontDoor door = new FrontDoor();
door.Changed += what => Console.WriteLine( quot;Log: {what}");
DoorScreen doorScreen = new DoorScreen(door);
door.Unlock();
Console.WriteLine("Maya closes the door screen");
doorScreen.Close();
door.Lock();
class FrontDoor
{
public event Action<string>? Changed; // the list, the adding and the removing, built in
public void Unlock() => Changed?.Invoke("front door unlocked");
public void Lock() => Changed?.Invoke("front door locked");
}
class DoorScreen
{
private readonly FrontDoor door;
public DoorScreen(FrontDoor door) { this.door = door; door.Changed += Show; }
private void Show(string what) => Console.WriteLine( quot;Door screen: {what}");
public void Close() => door.Changed -= Show; // -= takes it off the list
}
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
class FrontDoor {
private final List<Consumer<String>> listeners = new ArrayList<>();
// Subscribing hands back a way to unsubscribe.
Runnable subscribe(Consumer<String> listener) {
listeners.add(listener);
return () -> listeners.remove(listener);
}
void unlock() { tell("front door unlocked"); }
void lock() { tell("front door locked"); }
private void tell(String what) {
for (Consumer<String> listener : List.copyOf(listeners)) {
listener.accept(what);
}
}
}
class DoorScreen {
private final Runnable unsubscribe;
DoorScreen(FrontDoor door) { unsubscribe = door.subscribe(what -> IO.println("Door screen: " + what)); }
void close() { unsubscribe.run(); }
}
void main() {
FrontDoor door = new FrontDoor();
door.subscribe(what -> IO.println("Log: " + what));
DoorScreen doorScreen = new DoorScreen(door);
door.unlock();
IO.println("Maya closes the door screen");
doorScreen.close();
door.lock();
}
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
class FrontDoor:
def __init__(self):
self.listeners = []
def subscribe(self, listener):
"""Subscribing hands back a way to unsubscribe."""
self.listeners.append(listener)
return lambda: self.listeners.remove(listener)
def unlock(self):
self.tell("front door unlocked")
def lock(self):
self.tell("front door locked")
def tell(self, what):
for listener in list(self.listeners):
listener(what)
class DoorScreen:
def __init__(self, door):
self.unsubscribe = door.subscribe(lambda what: print(f"Door screen: {what}"))
def close(self):
self.unsubscribe()
door = FrontDoor()
door.subscribe(lambda what: print(f"Log: {what}"))
door_screen = DoorScreen(door)
door.unlock()
print("Maya closes the door screen")
door_screen.close()
door.lock()
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
// EventTarget is the list, built in: addEventListener, removeEventListener and dispatchEvent.
class FrontDoor extends EventTarget {
unlock() { this.dispatchEvent(new CustomEvent("change", { detail: "front door unlocked" })); }
lock() { this.dispatchEvent(new CustomEvent("change", { detail: "front door locked" })); }
}
class DoorScreen {
#leaving = new AbortController();
constructor(door) {
door.addEventListener("change", (event) => console.log(`Door screen: ${event.detail}`), { signal: this.#leaving.signal });
}
close() { this.#leaving.abort(); } // removes every listener added with this signal
}
const door = new FrontDoor();
door.addEventListener("change", (event) => console.log(`Log: ${event.detail}`));
const doorScreen = new DoorScreen(door);
door.unlock();
console.log("Maya closes the door screen");
doorScreen.close();
door.lock();
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
// EventTarget is the list, built in: addEventListener, removeEventListener and dispatchEvent.
class FrontDoor extends EventTarget {
unlock(): void { this.dispatchEvent(new CustomEvent("change", { detail: "front door unlocked" })); }
lock(): void { this.dispatchEvent(new CustomEvent("change", { detail: "front door locked" })); }
}
class DoorScreen {
#leaving = new AbortController();
constructor(door: FrontDoor) {
door.addEventListener("change", (event) => console.log(`Door screen: ${(event as CustomEvent<string>).detail}`), { signal: this.#leaving.signal });
}
close(): void { this.#leaving.abort(); } // removes every listener added with this signal
}
const door = new FrontDoor();
door.addEventListener("change", (event) => console.log(`Log: ${(event as CustomEvent<string>).detail}`));
const doorScreen = new DoorScreen(door);
door.unlock();
console.log("Maya closes the door screen");
doorScreen.close();
door.lock();
Log: front door unlocked
Door screen: front door unlocked
Maya closes the door screen
Log: front door locked
The same four lines again, and the front door shrank. In C#, Changed?.Invoke(...) uses the ?. from Null Object: an event nobody has subscribed to is null, so the call is skipped. In JavaScript and TypeScript, one abort() removes every listener a screen added with its signal, however many there are. In Java and Python, the screen keeps the function that subscribe handed back, not the listener; the loops go over a copy of the list (List.copyOf, list(...)), so a listener can safely unsubscribe while it's being told.
How it got its name
Nothing new got named here: this is still the Observer pattern from Pass 1, the one from the original 1994 book, with both halves now, joining and leaving. What's new is the bug's name: a listener left on the list after its owner is done is a lapsed listener, and it's one of the most common memory leaks in apps with screens. Languages built the pattern in because teams wrote the same list in every class: C# made it the event keyword, and browsers made it EventTarget.
Where you've already used it
button.addEventListener("click", ...)on a web page, andremoveEventListenerwhen a dialog closes.- C#'s
button.Click += OnClick, and-=in a window's close handler. - Angular's
subscribe(...), which hands back a subscription with anunsubscribe()method, exactly like the Java and Python versions above. - A phone app that stops location updates when you leave its map screen.
When not to use it
- When the listener lives as long as the thing it listens to. The activity log never closes, so it never needs to leave. Unsubscribing is for listeners that come and go.
- When there's exactly one listener, forever. A direct call is still easier to read, as Pass 1 said.
- When the listener is on another computer. An event is a list in one program's memory; the phone in Maya's pocket isn't in it. That's the next lesson.
The cost: every subscribe now needs a matching unsubscribe, and the place to put it (a screen's close, a component's destroy) is easy to forget. Tying listeners to one signal, as AbortController does, makes forgetting harder.
How often you'll meet it: every day (our estimate: every click handler and every screen that updates itself).
Check yourself
2 questions to try on the lesson page.
So what
A listener that joins must be able to leave. Use the tools your language already has for the list, and unsubscribe when the screen closes, with the very function you subscribed or the one subscribe handed back.