Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I unsubscribe after a complete?

Tags:

rxjs

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();});
like image 343
Bobby Avatar asked Jun 26 '19 07:06

Bobby


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) => {});
like image 163
Will Taylor Avatar answered Oct 11 '22 21:10

Will Taylor


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();
});
like image 27
Adrian Brand Avatar answered Oct 11 '22 22:10

Adrian Brand


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

like image 35
DongBin Kim Avatar answered Oct 11 '22 22:10

DongBin Kim