loading...
Cover image for RxJS finalize operator to execute logic on Observable termination
Angular

RxJS finalize operator to execute logic on Observable termination

juristr profile image Juri Strumpflohner Updated on ・1 min read

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
    }
  )

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;
    }
  )

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

Posted on by:

juristr profile

Juri Strumpflohner

@juristr

Architect πŸ‘¨β€πŸ’» @nrwl_io πŸ³πŸ¦„ β€’ Google Dev Expert #GDE β€’πŸŽ“ @eggheadio β€’ ❀ JS, Angular β€’ πŸ“ blogger β€’ πŸ—£οΈ speaker β€’ @cypress_io Ambassador β€’ nx.app β€’ nx.dev

Angular

This is where we write about all things Angular. It's meant to be a place for Angular community and people interested in Angular and the Angular ecosystem.

Discussion

markdown guide