Subscription represents an object that holds a disposable resource, usually the execution of an Observable.
A subscription has an important method, unsubscribe()
, which takes no parameters and simply handles the resources held by the subscription.
import { interval } from 'rxjs';
const observable = interval(1000);
const subscription = observable.subscribe((x) => console.log(x));
subscription.unsubscribe();
A Subscription essentially only has an
unsubscribe()
function to release resources or cancel the execution of an Observable.
Subscriptions can also be grouped together so that calling unsubscribe()
on one subscription can unsubscribe multiple subscriptions. This can be achieved by "adding" one subscription to another:
import { interval } from 'rxjs';
const observable1 = interval(300);
const observable2 = interval(400);
const subscription = observable1.subscribe((x) => console.log('first: ' + x));
const childSubscription = observable2.subscribe((x) => console.log('second: ' + x));
subscription.add(childSubscription);
setTimeout(() => {
subscription.unsubscribe();
}, 1000);
// Logs:
// first: 0
// second: 0
// first: 1
// second: 1
// first: 2
Subscriptions also have a method remove(otherSubscription)
to remove added child subscriptions:
import { interval } from 'rxjs';
const observable1 = interval(300);
const observable2 = interval(400);
const subscription = observable1.subscribe((x) => console.log('first: ' + x));
const childSubscription = observable2.subscribe((x) => console.log('second: ' + x));
subscription.add(childSubscription);
subscription.remove(childSubscription);
setTimeout(() => {
subscription.unsubscribe();
}, 1000);
// Logs:
// first: 0
// second: 0
// first: 1
// second: 1
// first: 2
// second: 2
// second: 3
// second: 4
// ...
As you can see, after the removal, the childSubscription
can still receive new values.