简体   繁体   中英

Observable best practice

In my current project I have an observable returning values and I have to update my local variable according to the value returned by the observable.

I see two ways of doing this, either by directly subscribing to my observable, or by using pipable operator.

According to your experience/knowledge, what is the best practice ?

1st approach (directly subscribing):

this.myObservable$.subscribe(value=> {
  this.myValue = value;
});

2nd approach (using pipable operator):

this.myObservable$.pipe(
    tap(value=> this.myValue = value)
  ).subscribe();

I think both are valid, but in this particular instance I would use the 1st approach and do the work in the subscribe block. The reason being that the intent is clearer.

"tap" is for doing side-effects, but you are not doing a side-effect here as there is no more logic going on after the tap. What you are doing is using the unwrapped final value to do something, and that is what the subscribe block is for.

I consider doing this within a pipe if a local variable has to be mandatory updated. I may have multiple subscriptions for the same observable and I may forget to update the local variable in any one of them. Taking care of this within the Observable is good.

myOb$ = this.myObservable$.pipe(
    tap(value=> this.myValue = value)
)

Just in your case, If you are not doing any changes in Observable, you can use, tap() instead of map()

Consider you want to update a variable of a class where the Observable exists not where it is subscribed then this is the way you go. Say, an Observable exists in a Service and multiple components are subscribing to it, after every emission, a variable of the service has got to be updated.

If the local variable belongs to the class subscribing the Observable, then of course there is no point in doing it within the pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM