Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger RXJS Stream only on certain condition

I have two tabs on my UI.

First tab (default), there is one input textbox and when user submits it, a http call is sent to server

Second tab - Same input textbox + list of checkboxes out of which at least one has to be selected. Then on submit http call is sent.

Both of these cases work fine by themselves.

Now, the problem is - I want my stream to trigger only when form is submitted and not on tab switch. However, I do want the value of tab clicked. However, currently after the form is submitted once, its being triggered on every tab switch as well ( probably because then it has both selected tab & account available).

Below is the code snippet.

I am not sure what i am missing. Any suggestions are highly appreciated.

detailsByAccount$: Observable<MyType> = this.selectedTab$.pipe(
switchMap((tab) => {
   //account$ = account submitted through form
  return this.account$.pipe(
    switchMap((account) => {
      alert(`${account} -------- ${tab}`);
      // Server Http call to get the response
      if (tab === 'X') {
        return this.myService.getDetails(account)  
      }
      return this.myService.getOtherDetails(account);
    })
  );
}),
);
like image 779
Vatsal Avatar asked Nov 20 '25 12:11

Vatsal


1 Answers

i would do it like this:

  detailsByAccount$: Observable<MyType> = this.account$.pipe(
    withLatestFrom(this.selectedTab$),
    switchMap(([account, tab]) => {
      alert(`${account} -------- ${tab}`);
      // Server Http call to get the response
      if (tab === 'X') {
        return this.myService.getDetails(account)  
      }
      return this.myService.getOtherDetails(account);
    })
  );

the withLatestFrom operator will not trigger the stream but when account$ is triggered, it will grab the latest value from selectedTab$ and pass it along. It will not trigger though if selectedTab$ has not emitted at least once.

like image 180
bryan60 Avatar answered Nov 22 '25 00:11

bryan60



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!