Search code examples
rxjsunsubscribe

Unsubscribe in rxjs


I'm new to rxjs. what is the problem with this code that subscribe method not work correctly.

this.http.postReq(this.api, data)
.subscribe((value) => {
  this.toastr.success(value, "Successfull");
  this.isLoading = false;
}, (err) => {
  this.toastr.error(err.error, "Error")
  this.isLoading = false;
}).unsubscribe();

}

but when remove ".unsubscribe()" its work correctly.

an example that work correctly in this manner.


Solution

  • To do this :

    let someSubscription = this.http.postReq(this.api, data)
    .subscribe((value) => {
      this.toastr.success(value, "Successfull");
      this.isLoading = false;
    someSubscription.unsubscribe();
    }, (err) => {
      this.toastr.error(err.error, "Error")
      this.isLoading = false;
    });
    

    So now , your request is unsubscribed after getting the response (which you want) .