Lessons4. Teardown and unsubscribe
Lessons · 04
4. Teardown and unsubscribe
Why you need to unsubscribe
Not every stream ends on its own. of(1, 2, 3) finishes in an instant, but interval(1000) will tick forever. Event handlers are the same: until you remove the listener, it keeps running.
In Angular this matters even more: a component leaves the screen, but if its subscription is still alive, the work carries on in the background. That's a memory leak. So RxJS gives us a way to cleanly "switch a stream off."
Glossary
- Subscription — the object that
.subscribe()returns. It has an.unsubscribe()method. - unsubscribe() — the command "switch this stream off for me." After you call it, no more values arrive.
- Teardown — the cleanup function. It's the function the Observable's recipe returns, and RxJS calls it when the subscription ends (via unsubscribe, complete, or error). This is where you typically stop timers, close sockets, and remove handlers.
What a teardown function looks like
new Observable(subscriber => {
// here — the startup work
return () => {
// here — the cleanup
};
});
Your task
- In the recipe function, make the first line log
'Subscribed'. - Send the value
'tick'withsubscriber.next('tick'). - At the very end of the recipe function, return an arrow function:
return () => console.log('Teardown');. That's the teardown. - Below the subscribe call, add
sub.unsubscribe();— that triggers the teardown.
Expected order: Subscribed → Value: tick → Teardown.
Solution spoiler · click to reveal
const { Observable } = Rx;
const stream$ = new Observable(subscriber => {
console.log('Subscribed');
subscriber.next('tick');
return () => {
console.log('Teardown');
};
});
const sub = stream$.subscribe(value => {
console.log('Value: ' + value);
});
sub.unsubscribe(); script.ts
CONSOLE · Console output
Hit Run to see the result...