Fire Action After async pipe has subscribed to an Observable

1.1k Views Asked by At

I have the following component:

data$: Observable < MyApolloQueryResult > ;

constructor(private myService: MyService) {}

ngOnInit() {
  this.data$ = this.myService.getData();
}
<div *ngIf="data$ | async as data; else loading">
  ...
</div>

As you can see I only subscribe to the Observable within the component template. The question is, how do I fire an action (like set a variable within myService above) only after the async pipe above has subscribed to the Observable, in other words, after having made sure this Observable is no longer cold.

1

There are 1 best solutions below

10
On BEST ANSWER

In order to have side-effects, use the do operator.

this.data$ = this.myService.getData().do(value => {
  // side effect
})

The function passed to do operator will be called each time the observable emits, for each subscription -- so be careful to subscribe only once, or he effect will happen multiple times.


However, this usually means that you're not using the power of RxJS completely. Instead of doing a side-effect, try using some of the operators to manipulate the stream the way you'd like.