Unknwn  Artist
Unknwn Artist

Reputation: 460

Angular Observable Unsubscribe where?

I have a doubt on where I should unsubscribe from an Observable.

I have following function in a component:

  loadProjectDetails(projectId: number): void {

console.log('>> loadProjectDetails(), id=', projectId);

const subscription = this.projectService.getProjectById(projectId).subscribe(
  data => {

    this.component = ProjectComponent;
    this.injector = Injector.create([{provide: Project, useValue: data}], this.inj);
    this.localStorageService.setLastSelection(projectId, null, null);
    subscription.unsubscribe();

  }, error => {

    if (error.status === 400) {
      alert("There is no project with id=" + projectId);
    } else {
      throw error;
    }
    subscription.unsubscribe();

  }
);
}

Does it make any sense to unsubscribe in the presented way or it is enough to unsubscribe in ngOnDestroy() method?

The loadProjectDetails(projectId: number) method fires up every time user hits a button, so it runs multiple times before the component will be destroyed.

Upvotes: 0

Views: 123

Answers (2)

Arne
Arne

Reputation: 842

You shouldn't manually unsubscribe, 90% of the time. In this specific case, you're using a service to fetch data. If this service uses an http call, and thus the HttpClient, the observable is already closed once the call is finished and closed observables are already unsubscribed. If this is not the case, you'd only need the first element, and first or take(1) is the way to go.

Upvotes: 1

JuanF
JuanF

Reputation: 876

Unsubscribing in the ngOnDestroy would be more than enough for the majority of the components. However, if you only need your observable for something specific and you would use it just once in a component with a long life, you can use the solution you have to save resources, but for just one observable there isn't a high impact

Upvotes: 0

Related Questions