9

Question - based on the Angular doc, when is it more appropriate to use next vs complete for my observable?

I'm looking through someones Angular 7 project and I see a lot of code that looks like this below where some calls use next and some just use complete and I'm trying to know when to use the appropriate one based on the Angular doc, because next is 'required' and complete is 'optional'.

login() {
  this.authService.login(this.model).subscribe(next => {
    this.alertService.success('Logged in successfully');
  }, error => {
    this.alertService.danger(error);
  }, () => {
    this.router.navigate(['/home']);
  });
}

register() {
  this.authService.register(this.user).subscribe(() => {
      this.showRegistrationComplete = true;
    }, error => {
      // handle the error code here
    }
  );
}

Where in some cases I see 'next' and some cases I see '()' complete for the subscribe.

Both of these 2 calls above call these below (post methods to a controller)

login(model: any) {
    return this.http.post(this.baseUrl + 'login', model).pipe(
      map((response: any) => {
        const user = response;
        if (user) {
          // do some stuff
        }
      })
    );
  }

  register(model: any) {
    return this.http.post(this.baseUrl + 'register', model);
  }

What happens if I have this below - does this mean 'complete' or does this mean 'next' because it's the first parameter in the subscribe?

this.authService.login(this.model).subscribe(() => {
      this.alertService.success('Logged in successfully');
      this.router.navigate(['/home']);
    }, error => {
      this.alertService.danger(error);
    });
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • I have no clue when i'm using completing Observable or endless loop to ;] Know that when You subscribe once to completable Observable it become null. And endless Observable You need to allways unsubscribe. – Mises Oct 01 '19 at 15:55

2 Answers2

13

From RxJS documentation:

Subscribing to an Observable is like calling a function, providing callbacks where the data will be delivered to.

An observable can send three types of notifications: Next, Error, Complete.

  • Next notification sends a value such as a Number, a String, an Object, etc.

  • Error notification sends a JavaScript Error or exception.

  • Complete notification does not send a value.

And in subscribe() method we provide three callbacks to receive these three types of notifications. Order of the callbacks matter, they correspond to Next, Error, and Complete in order.

In the code below, the parameter next in the first callback can be named anything, its name doesn't have any significance.

this.authService.login(this.model).subscribe(next => {
  this.alertService.success('Logged in successfully');
});

When there is no parameter in first callback, we aren't capturing the values sent from the observable. We can ignore having a parameter when we are only concerned with knowing that a value is sent but don't care about the actual value sent.

this.authService.login(this.model).subscribe(() => {
      this.alertService.success('Logged in successfully');
      this.router.navigate(['/home']);
    }, error => {
      this.alertService.danger(error);
    });

In above code snippet, we won't receive the values sent but the alert is triggered whenever a value is sent. Here we don't have the third callback, so we won't be notified when the observable completes.

When is it more appropriate to use next vs complete for my observable?

  • Use the first callback to receive values from an observable.

  • Use second callback for handling any errors.

  • Use third callback to perform any tasks when the observable completes.

Also note that Error and Complete notifications may happen only once during the observable execution, and there can only be either one of them. So when there is an error, the third callback won't be called.

Nikhil
  • 6,493
  • 10
  • 31
  • 68
  • Hi Nikhil. So I just want to make sure that when I don't provide a value for the first callback '()' that it's still using next? I'm just curious about the ordering: next, error, complete. Does the ordering matter? – chuckd Oct 01 '19 at 16:56
  • @user1186050 - Yes, it is still using `next`. Ordering of the callbacks matter, they correspond to `next`, `error`, and `complete` in order. – Nikhil Oct 01 '19 at 17:13
0

Found some interesting bits that complements the existing answer:

What Is an Observer?

An observer is the consumer of the data produced by the observable. It is represented by an object with next, error and complete properties. These properties contain callback functions for processing data, handling errors and completion notifications.

The subscriber function emits data to the observer by calling the next() callback function. Likewise, it can send an error notification by calling the error() callback and a completion notification by calling the complete() callback.

Observers

To subscribe to an observable, we call the observable’s subscribe() method and pass in an observer or a next() callback as an argument.

What is an observer in RxJS?

An observer is an object of type observer with the next , error and complete methods:

export interface Observer<T> {  
  next: (value: T) => void;  
  error: (err: any) => void;  
  complete: () => void;  
}
jumping_monkey
  • 5,941
  • 2
  • 43
  • 58