Do Subscription instances without reference handles need to be unsubscribed?

Viewed 170

Just curious whether Subscription instances that are not referenced need to be unsubscribed? For example this demo calls:

onSubmit(creds: Creds) {
   this.authService.login(creds).subscribe();
}

So each time the someone logs in a Subscription instance is created and returned, but there are no handles to it.

IIUC these will just be garbage collected, but figure I'd double check just to be on the safe side.

1 Answers

If the Observable completes then there is no need to unsubscribe. Observables created with the http service will complete after calling.

That said it is still best to unsubscribe or have a takeUntil clause.

finalise = new Subject<void>();

onSubmit(creds: Creds) {
  this.authService.login(creds).pipe(takeUntil(finalise)).subscribe();
}

ngOnDestroy() {
  this.finalise.next();
  this.finalise.complete();
}

This way you can use the same subject to complete all your Observables instead of managing many subscriptions.

Related