Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complete callback in Observable.prototype.subscribe in Angular 2

The complete callback does not work as expected. Let me explain:

See this picture, note the complete callback in subscribe method. This complete function is only called when the observerOrNext is called. When some error happens, the complete is not called. This is right? There are another method to get a callback that always is called when the process finish?

enter image description here

Example:

When success:

this.getData(params)
    .subscribe(
        successData => {
            // this is called
        },
        error => {
            // this is not called. Ok!
        },
        () => { // when complete
            // this is called, ok!
        }
    );

When error:

this.getData(params)
    .subscribe(
        successData => {
            // this is not called, ok!
        },
        error => {
            // this is called. Ok! Yeah!
        },
        () => { // when complete
            // this is not called, why god??
        }
    );
like image 664
Marcos Kubis Avatar asked Feb 26 '26 06:02

Marcos Kubis


1 Answers

For rxjs 6 use pipe/finalize:

import { finalize } from 'rxjs/operators';

this.getData(params)
  .pipe(
    finalize(() => {
      // this is called on both success and error
    })
  )
  .subscribe(
    (successData) => {  },
    (err) => {  }
  );
like image 148
Markus Pscheidt Avatar answered Feb 27 '26 19:02

Markus Pscheidt



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!