Unsubscribe in subscribe callback function?

A more RxJS-ish way of doing what you want is to make use of the take operator, like this:

this.puzzleService.login(this.nameoremail, this.password).pipe(
  take(1)
).subscribe(success => {
  // ...
});

This will make the observable emit exactly one value and then complete it.

However, @Picci is totally right that if your login method returns a result from a HttpClient request, you don't need to unsubscribe manually (nor use take, for that matter).


Unsubscribing is important to avoid memory leaks, but it maybe not so important if you are "just wanting the ONE response from backend".

What I mean is that if, behind your this.puzzleService.login you are using the Angular http service, than you do not have to worry about unsubscribing since the service itself unsubscribes as soon as it gets the response from the backend, or an error occurs.

Unsubcribing is important when you face Observable streams which emit, by their nature, more than one value, and this is not the case of an http call but may be the case of web-sockets streams or other kind of streams.

This article from Ben Lesh, top contributor if not lead of RxJS, casts some light on the topic.

Tags:

Angular

Rxjs