What is Subscription?
Subscription in RxJS is an object that appears when you subscribe to an Observable. It manages the connection between the stream and your code.
Example:
ts
import { interval } from 'rxjs';
const stream$ = interval(1000);
const subscription = stream$.subscribe(value => {
console.log('Tick:', value);
});Here:
subscriptionis the Subscription itself- it "connects" you to the stream
Why it's needed:
To unsubscribe, meaning stop the stream and free up resources.
ts
subscription.unsubscribe();If you don't do this, the stream can run forever (for example, interval()),
and cause a memory leak or unnecessary load.
Where it's used:
- In Angular components (
ngOnDestroy) - When working with infinite streams
- To manually control when the stream should stop
Conclusion:
Subscription is like a remote control for an Observable. You subscribe, you get data. You unsubscribe, the stream stops.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.