How to subscribe to switchMap

Viewed 36

Given a switchMap like this

const sw = switchMap(() => {
    if (/*some condition*/) { return this.getDetails().pipe(...) }
    return this.getOtherDetails().pipe(....);
});

Ideally I would like to use this, for example as follows

from(sw).subscribe(....)

but that doesn't work :)

So how can I do this. I can think of one solution

of(true).pipe(sw).subscribe(...)

But this doesn't feel right, or does it? I can image RxJS has a much better solution for this kind of problem. Any suggestions?

2 Answers

@martin's comment is right.

The reason it doesn't feel right is because you're not starting with an event or anything you're waiting for. You might as well have a method like

getAppropriateDetails$() {
  if (/*some condition*/) {
    return this.getDetails$();
  }
  this.getOtherDetails$();
});

and then you can use it like

this.getAppropriateDetails$().pipe(
  ...
).subscribe (
  ...
)

You can just use tenary operator.

([some condition] ? this.getDetails().pipe(...) : this.getOtherDetails().pipe(...)).subscribe(...);
Related