jonassvensson
jonassvensson

Reputation: 491

RxJS: switchMap inside merge doesn't work to make a conditional observable return

Inside a merge I want the first observable to be conditional between two different ones, but it seems adding a switchMap inside a merge doesn't work.

I don't understand why the switchMap inside the merge never triggers and only handle pure observables.

switchMap(() => {
       return merge(
          switchMap(() => {
            if (condition) {
              return of(something);
            }
            return of(somethingelse);
          }),
         obs2$
        );
      })

Upvotes: 1

Views: 473

Answers (1)

SnorreDan
SnorreDan

Reputation: 2890

Merge takes Observables as it's arguments, but SwitchMap is not a function that creates an Observable. SwitchMap is a pipeable operator that goes inside a pipe().

One way of solving this problem would be:

switchMap(() => {
  let myVar;
  if (condition) {
    myVar = something;
  } else {
    myVar = somethingelse;
  }
  return merge(
    of(myVar), 
    obs2$
  );
})

Upvotes: 1

Related Questions