0

I have the code below:

data$ = getResponse1$.pipe(
        tap((res1: any) => {
          this.qService.data = res1;
        }),
        switchMap(() =>
          of(getResponse2$(res2)).pipe(
            map((val) => {
              const res: any = {
                val,
              };
              return res;
            })
          )
        )
      );

Is it possible to run getResponse1$ i.e. the first observable, along with getResponse2$ only when a condition is true? Otherwise, I want to execute only getResponse2$.

  • Could you please clarify what the exact desired behaviour is? What should be emitted by this Observable and under which circumstances? – Will Alexander Mar 07 '22 at 17:17
  • what is the condition – Chamika Sandamal Mar 07 '22 at 17:18
  • @WillAlexander I want to handle the data of a tree. If the level of the current node is 1, I want to run both observables. If the level of the current node is > 1, I want to execute only the second observable, i.e. getResponse2$. – George Perid Mar 07 '22 at 17:27
  • @ChamikaSandamal if(level === 1) I want to run the code mentioned above. If(level > 1) I want to run the second part of the code above i.e. only getResponse2$. I wanted to avoid writing twice the code in an if..else block. – George Perid Mar 07 '22 at 17:30

1 Answers1

0

Take a look at: Conditional concat in RXJS?

Adopting it to your case:

getResponse2$.pipe(
  switchMap(response => [your_condition] ? of(response).pipe(withLatestFrom(getResponse1$)) : of(response))
);

You will get an array as output if condition is true, where the first element of array corresponds to getResponse2$ result value, and second one to getResponse2$. Otherwise you will get just getResponse2$ result value.

Vlad
  • 985
  • 1
  • 6
  • 10