Menu
Coddy logo textTech

Observer Pattern

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 44 of 57.

In the observer pattern, an object (the subject) keeps a list of observers and notifies all of them when something happens. The subject does not need to know what the observers do:

final class Button {
    private var handlers: [(String) -> Void] = []

    func onTap(_ handler: @escaping (String) -> Void) {
        handlers.append(handler)
    }

    func tap() {
        for h in handlers { h("tapped") }
    }
}

let b = Button()
b.onTap { print("logger saw \($0)") }
b.onTap { print("counter saw \($0)") }
b.tap()

Output:

logger saw tapped
counter saw tapped

Observers can also be objects that conform to a protocol. The subject calls the protocol method on each registered observer:

protocol StockObserver: AnyObject {
    func priceChanged(_ symbol: String, to price: Int)
}

final class Stock {
    let symbol: String
    private var observers: [StockObserver] = []
    var price: Int { didSet { observers.forEach { $0.priceChanged(symbol, to: price) } } }
    init(symbol: String, price: Int) { self.symbol = symbol; self.price = price }
    func add(_ o: StockObserver) { observers.append(o) }
}

final class Alert: StockObserver {
    func priceChanged(_ s: String, to p: Int) { if p > 100 { print("\(s) above 100: \(p)") } }
}

let apple = Stock(symbol: "AAPL", price: 90)
apple.add(Alert())
apple.price = 95
apple.price = 120

Output:

AAPL above 100: 120

Observers usually need a way to stop listening. Returning an id (or token) from the registration lets the caller remove its observer later:

final class EventBus {
    private var listeners: [Int: (String) -> Void] = [:]
    private var nextId = 0

    func subscribe(_ f: @escaping (String) -> Void) -> Int {
        nextId += 1
        listeners[nextId] = f
        return nextId
    }
    func unsubscribe(_ id: Int) { listeners[id] = nil }
    func publish(_ event: String) {
        for id in listeners.keys.sorted() { listeners[id]!(event) }
    }
}

let bus = EventBus()
let a = bus.subscribe { print("A got \($0)") }
_ = bus.subscribe { print("B got \($0)") }
bus.publish("login")
bus.unsubscribe(a)
bus.publish("logout")

Output:

A got login
B got login
B got logout

@escaping marks a closure that is stored and called later, after the function that received it has returned. The observer pattern keeps the subject and the observers loosely connected: new observers can be added without changing the subject.

func onTap(_ handler: @escaping (String) -> Void) {
    handlers.append(handler)   // stored: must be @escaping
}
challenge icon

Challenge

Easy

Complete the class Newsletter, a subject that sends issues to subscribers. subscribe(name:handler:) stores a closure under a name (subscribing again with the same name replaces it), unsubscribe(name:) removes it, and publish(_ title:) calls every handler in alphabetical order of name and returns how many were notified.

The supplied code reads commands sub <name>, unsub <name> or pub <title>. Each subscriber's handler prints <name> reads <title>; after each pub the code prints sent to 2.

Your code goes in Newsletter.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let news = Newsletter()
for cmd in input {
    let p = cmd.split(separator: " ", maxSplits: 1).map(String.init)
    switch p[0] {
    case "sub":
        let name = p[1]
        news.subscribe(name: name) { print("\(name) reads \($0)") }
    case "unsub": news.unsubscribe(name: p[1])
    default: print("sent to \(news.publish(p[1]))")
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Swift playground