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

4

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay