Lesson 2 · Unit 04
Observer
Announce what happened to whoever cares
What you practise
- Events and subscribers, publish and subscribe, decoupling the source from who cares, forgotten unsubscribes
Try a question from this lesson
Pick one
Marketing wants a text message for every order too, and something else next month. What is wrong with how this function is growing?
def place(order):
save(order)
send_email(order)
update_stock(order)
log_stats(order)function place(order) {
save(order);
sendEmail(order);
updateStock(order);
logStats(order);
}function place(order: string) {
save(order);
sendEmail(order);
updateStock(order);
logStats(order);
}Correct answer
It is edited for every new reaction to an order
Why
Placing an order has one reason to change, yet this function also changes whenever anyone wants to react to an order. It knows email, stock and statistics by name, and the list only gets longer.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Observer
Turn the call around. The source keeps a list of functions and calls each one when something happens. Whoever cares adds a function to the list.
The source no longer names its listeners. A new reaction is one new subscription, with no edit to the source.
subs = []
def on(fn):
subs.append(fn)
def emit(x):
for fn in subs:
fn(x)const subs = [];
function on(fn) {
subs.push(fn);
}
function emit(x) {
for (const fn of subs) fn(x);
}type Sub = (x: number) => void;
const subs: Sub[] = [];
function on(fn: Sub) {
subs.push(fn);
}
function emit(x: number) {
for (const fn of subs) fn(x);
}TypeScript note(x: number) => void accepts any function that takes a number. Whatever it returns is ignored, so (x) => list.push(x) fits too.
Concept
The forgotten unsubscribe
The list holds a reference to every function that was added to it.
A screen that subscribes when it opens and never unsubscribes stays reachable after it closes. Its memory is not freed, and its handler keeps running for a screen that nobody can see.
Rule: whoever subscribes also unsubscribes, at the point where it is torn down.
9 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.