Niek
Niek

Reputation: 1607

Promise 'finally' callback equivalent in RxJS

I have a component that fetches some data from an API. The component has a loading member variable, which is used to determine whether a loading icon should be shown. When the data fetch completes, loading is set to false, in order to hide the loading icon. This should happen regardless of whether an error occurred or not.

Currently, I have implemented this as follows:

export class MyComponent implements OnInit {

  loading = true;
  data;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getData().subscribe(data => {
      this.data = data;
      this.loading = false;
    },
    () => {
      this.loading = false;
    });
  }

}

I'm wondering if there is a way to eliminate the duplication of this.loading = false. If I were using Promises, this is what I'd use the Promise.finally() callback for -- but I'm not. Is there an equivalent in RxJS, or a better way to implement this?

Upvotes: 4

Views: 1443

Answers (1)

Stevethemacguy
Stevethemacguy

Reputation: 756

As of RXJS 5.5, use the "finalize" operator:

ngOnInit() {
  this.dataService.getData()
  .pipe(
    finalize(() => this.loading = false)
  )
  .subscribe(data => {
    this.data = data;
  });
}

Upvotes: 5

Related Questions