RxJS Tip: Understand the Terminology: Subscription

Deborah Kurata - Nov 16 '20 - - Dev Community

A key concept when using RxJS is Subscription.

What Is a Subscription?

A Subscription is an object that represents execution of an Observable.

Like the days of old when you couldn't get a newspaper delivered unless you subscribed, Observables don't do anything until a consumer subscribes.

For example, if your component (the consumer) wants to be notified when an Observable emits the response returned from an Http call, the component subscribes to that Observable.

How Do You Subscribe?

One way to subscribe to an Observable is with its subscribe method.

const sub = source$.subscribe();
Enter fullscreen mode Exit fullscreen mode

That method tells the Observable to start emitting AND creates and returns a Subscription.

It's good practice to unsubscribe from any Observable you subscribe to.

How Do You Unsubscribe?

Use the unsubscribe method of a Subscription to unsubscribe. The unsubscribe method lets the Observable know that the consumer no longer wants to receive emissions or notifications.

const sub = source$.subscribe();

sub.unsubscribe();
Enter fullscreen mode Exit fullscreen mode

Let's examine a more concrete example.

Here is an Http request in a service:

  products$ = this.http.get<Product[]>(this.productsUrl)
    .pipe(
      tap(data => console.log(JSON.stringify(data))),
      catchError(this.handleError)
    );
Enter fullscreen mode Exit fullscreen mode

Here is the subscription in a component:

ngOnInit(): void {
  this.sub = this.productService.products$.subscribe(
     products => this.products = products
  );
}
Enter fullscreen mode Exit fullscreen mode

Here is the unsubscribe in the component:

ngOnDestroy(): void {
  this.sub.unsubscribe();
}
Enter fullscreen mode Exit fullscreen mode

Once Subscribed, How Do You Capture the Emissions/Notifications?

To perform an operation when an item is emitted from an Observable, an error occurs, or the Observable is complete, you need an Observer, discussed in a later tip.

I hope that's clarified the meaning of the term Subscription.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .