Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Subscription instances without reference handles need to be unsubscribed?

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.

like image 979
Ole Avatar asked Oct 21 '25 10:10

Ole


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.

like image 82
Adrian Brand Avatar answered Oct 23 '25 01:10

Adrian Brand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!