Learnitweb

Subscription in RxJS

1. Introduction

A Subscription is an object that represents a disposable resource. Calling the subscribe() on an Observable object returns a Subscription object. Subscription has method unsubscribe() which disposes the resource held by the Subscription.

import { Observable } from "rxjs";
const observable = new Observable(function subscribe(subscriber) {
  subscriber.next(1);
  subscriber.next(2);
});
const subscription = observable.subscribe((error) => console.log(error));
subscription.unsubscribe();

2. Methods of Subscription

A Subscription object has two important methods:

  • unsubscribe(): This method does not take any argument and disposes the resource held by the subscription.
  • remove(subscription): This method is used to undo the addition of a child Subscription.

3. Unsubscribing multiple Subscriptions

The unsubscribe() method can unsubscribe multiple Subscriptions. Subscriptions can be added together. The Subscription added to another Subscription is also known as the Child Subscription of that Subscription. Calling unsubscribe() on the parent Subscription unsubscribes both parent and child Subscriptions.

import { interval } from "rxjs";

const observable1 = interval(300);
const observable2 = interval(200);

const subscription = observable1.subscribe((x) => console.log("first observable value: " + x));
const childSubscription = observable2.subscribe((x) =>
  console.log("second observable value: " + x)
);

subscription.add(childSubscription);

setTimeout(() => {
  // Unsubscribes both parent and child subscriptions
  subscription.unsubscribe();
}, 1000);