Should I unsubscribe after a complete?

You should not unsubscribe in a subscription, it the observable emits instantly then sub is undefined.

If you want a self unsubscribing observable you can use takeUntil

finalise = new Subject();
this.service.getElevation(value).pipe(takeUntil(finalise)).subscribe((e) => { 
  finalise.next();
  finalise.complete();
});

In your case you don't need to unsubscribe.

All Observers will automatically be unsubscribed when you call complete. That said, you may want to implement your consuming (component) code do handle the possibility that the implementation of the service may change in the future.

You could do this by using the take operator which will unsubscribe after the first value is emitted:

this.service.getElevation(value).pipe(take(1)).subscribe((e) => {});

Brief note:

  • Try to control the subscription with operators such as takeUntil.
  • You don’t need to unsubscribe yourself if the sender(Subject) completes.
  • For your case, since the sender returned by getElevation function completes itself after emitting a value one time, you don’t need to either use any operator or unsubscribe yourself to unsubscribe it.

All you have to do: this.service.getElevation(value).subscribe((v) => // do what you want);

Tags:

Rxjs