Should I unsubscribe after a complete?

Viewed 3792

I have a quick question about observable.

I have the following observable:

  getElevation(pos: Cartographic): Observable<Cartographic> {
    return new Observable(observer => {
      const promise = Cesium.sampleTerrain(this.terrainProvider, 11, Cesium.Cartographic(pos.longitude, pos.latitude))
      Cesium.when(promise, (updatedPositions) => {
        observer.next(updatedPositions);
        observer.complete();
      });
    });
  }

In a component I have:

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

My question is, this is a one shoot observable, so I complete just after, is the complete automatically close the subscription? or, do I also have to do this:

const sub = this.service.getElevation(value).subscribe((e) => {sub.unsubscribe();});
3 Answers

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) => {});

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();
});

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);

Related