Observer
Definition
Publisher and subscriber
- In plain English
- A publisher announces events, and a subscriber is code that has asked to be told about them.
- Think of it like
- Like a radio station and its listeners.
Observer
- In plain English
- Observer lets many subscribers register interest in an event, and the publisher notifies all of them when it happens.
- Think of it like
- It is like signing up for a delivery app's notifications instead of checking the doorstep every five minutes.
Unsubscribe
- In plain English
- Unsubscribing removes a subscriber so it stops receiving events.
- Think of it like
- Like cancelling a newsletter.
Why it exists
A checkpoint service directly calls the leaderboard, family tracker and photo service. Adding another listener means editing the checkpoint service.
Let interested code register instead. The publisher announces an event without listing each reaction inside its business logic.
How it works
Callback
- In plain English
- A callback is a function you register so other code can call it later.
- Think of it like
- It is like leaving your phone number for a call when your order is ready.
package hub
import "sync"
type Event struct{ Name string }
type Listener func(Event)
type Hub struct {
mu sync.Mutex
next int
listeners map[int]Listener
}
func (h *Hub) Subscribe(fn Listener) func() {
h.mu.Lock()
if h.listeners == nil {
h.listeners = make(map[int]Listener)
}
id := h.next
h.next++
h.listeners[id] = fn
h.mu.Unlock()
return func() { h.mu.Lock(); delete(h.listeners, id); h.mu.Unlock() }
}
func (h *Hub) Publish(e Event) {
h.mu.Lock()
snapshot := make([]Listener, 0, len(h.listeners))
for _, fn := range h.listeners {
snapshot = append(snapshot, fn)
}
h.mu.Unlock()
for _, fn := range snapshot {
fn(e)
}
}
Leaderboard and FamilyTracker subscribe to Hub, which notifies registered Listener functions.
Channel
- In plain English
- A channel is a Go value used to send typed values between parts of a program.
- Think of it like
- It is like a conveyor belt carrying messages from a sender to a receiver.
- Publish copies listeners while holding the mutex, then releases it before calling them. Callbacks can therefore subscribe or unsubscribe.
- Unsubscribe prevents inclusion in later snapshots. An event already copied for delivery may still arrive.
- Separate channels need space for waiting values and a rule for full channels. Separation alone does not prevent blocking.
Examples
Notify every interested service
A smoke event triggers SMS alerts, the map and fire crews. A drone dispatcher joins with another Subscribe call.
package main
import "fmt"
type Listener func(string)
type Hub struct{ listeners []Listener }
func (h *Hub) Subscribe(fn Listener) { h.listeners = append(h.listeners, fn) }
func (h *Hub) Publish(event string) {
for _, fn := range h.listeners {
fn(event)
}
}
func main() {
h := &Hub{}
for _, service := range []string{"SMS", "map", "crew", "drone"} {
h.Subscribe(func(e string) { fmt.Println(service, e) })
}
h.Publish("smoke at zone 4")
}
This single-threaded demonstration calls every listener directly. The protected hub above is the starting point when registration and publishing may overlap.
The insight
Publishers do not need to know who is listening.
Publish a crossing once
Each checkpoint crossing interests the leaderboard, family tracker and photo matcher. Timing code publishes one Crossing value.
package main
import "fmt"
type Crossing struct {
Runner string
Checkpoint int
}
type Listener func(Crossing)
type Hub struct{ listeners []Listener }
func (h *Hub) Subscribe(fn Listener) { h.listeners = append(h.listeners, fn) }
func (h *Hub) Publish(e Crossing) {
for _, fn := range h.listeners {
fn(e)
}
}
func main() {
h := &Hub{}
for _, service := range []string{"leaderboard", "family tracker", "photo matcher"} {
h.Subscribe(func(e Crossing) { fmt.Println(service, e.Runner, e.Checkpoint) })
}
h.Publish(Crossing{"R42", 3})
}
This single-threaded demo delivers callbacks in registration order. The reusable map-based hub above intentionally promises no order.
The insight
New consumers plug in without touching timing code.
Keep a slow logger from blocking displays
Temperature changes notify the display, phone and logger through separate channels. The logger falls behind for one reading.
package notifications
import "fmt"
type Event struct{ Celsius int }
type Hub struct{ subscribers []chan Event }
func (h *Hub) Subscribe() <-chan Event {
ch := make(chan Event, 1)
h.subscribers = append(h.subscribers, ch)
return ch
}
func (h *Hub) Publish(e Event) int {
dropped := 0
for _, ch := range h.subscribers {
select {
case ch <- e:
default:
dropped++
}
}
return dropped
}
func Demo() {
h := &Hub{}
display, phone, logger := h.Subscribe(), h.Subscribe(), h.Subscribe()
h.Publish(Event{20})
<-display
<-phone
fmt.Println("dropped", h.Publish(Event{21}))
fmt.Println("display", <-display, "phone", <-phone, "logger", <-logger)
}
Each channel holds one event. Nonblocking sends drop a new reading when full; this suits disposable readings, not critical alerts.
The insight
Channels need an explicit policy for slow subscribers.
Trade-offs
Pros
- One event supports many reactions.
- New listeners register independently.
- Publisher code stays focused.
Cons
- Reactions are harder to trace.
- Ordering and failure rules need decisions.
- Forgotten subscriptions retain data.
Use when
- Several independent consumers react to one event.
- Listeners change without changing the publisher.
Avoid when
- One consumer needs an immediate result.
- A direct call already expresses the required order.
Quick check
Takeaways
- Observer = publish once, many subscribers react.
- Publishers don't know their listeners.
- Protect the subscriber list and watch for slow subscribers.