Home > Back-end >  How do I execute methods based on which observable is emitted? But at first, I need to depend on bot
How do I execute methods based on which observable is emitted? But at first, I need to depend on bot

Time:03-15

 combineLatest(data$, order$).subscribe(([data, order]: any) => {
  if (order && data) {
    this.setData(data);
    this.setOrder(order);
  }
});

The current scenario is that-we wait for data$ and order$ to return observables-data and order, and using data and order, we perform two methods- this.setData(data) and this.setOrder(order);

this.setOrder(order) depends on this.setData(data) initially.

My expectation is, On ngOnInit the same behaviour initially, but on successive emission of observables(due to change in state(triggered within the ngOnInit))-
something like-

if change in data${
    Dont call this.setOrder(order); call this.setData(data);
}and if change in order${
    Dont call this.setData(data); call this.setOrder(order);
}

Thank you in advance.

CodePudding user response:

If you go with combineLatest, then you loose the information about which observable emitted the value, because combineLatest will emit the latest value from all the source observables (given that both emitted at least one value). To overcome this, and still keep your behavior (setData and setOrder when both are available), you could do something like this:

const orderData$ = combineLatest(data$, order$).pipe(
  filter(([data, order]) => !!data && !!order),
  first()
);

data$.pipe(skipUntil(orderData$)).subscribe(data => {
  this.setData(data);
});
order$.pipe(skipUntil(orderData$)).subscribe(order => {
  this.setOrder(order);
});

orderData$.subscribe(([data, order]) => {
  this.setData(data);
  this.setOrder(order);
});

The skipUntil operator causes the observable stream to skip the emission of values ​​until the passed in observable emits the first value.

  • Related