DEV Community

Cover image for RxJS finalize operator to execute logic on Observable termination
Juri Strumpflohner for Angular

Posted on • Edited on • Originally published at egghead.io

RxJS finalize operator to execute logic on Observable termination

In this article we're going to have a look at the RxJS finalize operator. To have a practical use case, let's take a look at disabling/enabling a form submit button during an HTTP request.

Disabling/enabling a button during an Angular HTTP request

Let's take a look at an RxJS Observable subscription:

this.someService.fetchDataFromApi()
  .subscribe(
    result => {
      // success
    },
    err => {
      // some error happened
    }
  )
Enter fullscreen mode Exit fullscreen mode

Assume this call is triggered by a button click on our form. Many people still double-click on those buttons and we definitely want to prevent 2 calls being sent to our backend API. There are different ways to avoid that of course, but for the purpose of this example, let's go the route of disabling the button once it has been clicked, and re-enable it when the http call terminates.

this.isLoading = true;
this.someService.fetchDataFromApi()
  .subscribe(
    result => {
      // success
      this.isLoading = false;
    },
    err => {
      // some error happened
      this.isLoading = false;
    }
  )
Enter fullscreen mode Exit fullscreen mode

Whenever isLoading is set, we disable our button on the form. Now as in the example before, the isLoading = false instruction is duplicated, because we want to re-enable the button in both, success and error cases.

Read more »


TL;DR: Here's the corresponding Egghead lesson

Check out my corresponding Egghead video

Top comments (0)