What does add() do on Subscription?
The .add() method on Subscription lets you combine several subscriptions into one.
This is useful so you can later unsubscribe from all of them at once by calling .unsubscribe() on the main one.
Example:
ts
const sub1 = interval(1000).subscribe(val => console.log('A', val));
const sub2 = interval(500).subscribe(val => console.log('B', val));
sub1.add(sub2); // now sub2 is "linked" to sub1
// later:
sub1.unsubscribe(); // unsubscribes both sub1 and sub2When it's useful:
- When you have several subscriptions in one place (for example, in a component)
- So you don't have to write
unsubscribe()for each subscription manually
Conclusion:
.add() on Subscription is a way to group subscriptions
so you can then manage them as one. Convenient and safe.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.