Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 575
Niek Avatar asked Nov 15 '25 10:11

Niek


1 Answers

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

ngOnInit() {
  this.dataService.getData()
  .pipe(
    finalize(() => this.loading = false)
  )
  .subscribe(data => {
    this.data = data;
  });
}
like image 125
Stevethemacguy Avatar answered Nov 17 '25 23:11

Stevethemacguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!