0
votes

I have two observables:

this.one$ = this.httpClient.get<any>();
this.tow$ = this.httpClient.get<any>();

I need to get third observable as result by condition:

if (url == "one) {
    this.result$ = this.one$;
} else if (url == "two") {
    this.result$ = this.two$;
}

Using in template:

{{ result | async }}

How to do this more elegant using Rxjs?

2

2 Answers

2
votes

You could use the RxJS iif conditional function. Try the following

import { iif } from 'rxjs';

this.result$ = iif(() => url === "one", this.one$, this.two$);

From docs:

Decides at subscription time which Observable will actually be subscribed.

So if you were to subscribe in the controller (instead of using async pipe), you could dynamically change the condition before subscription.

url: string;
this.result$ = iif(() => url === "one", this.one$, this.two$);

url = 'one';
this.result$.subscribe(...);      // <-- this.one$;

url = 'two'
this.result$.subscribe(...);      // <-- this.two$;
0
votes

For your problem, I see two different solutions:

The first one is zipping them and return one of them in a pipe:

const url = 'one';
const first$ = of('one');
const two$ = of('two');

zip(first, two).pipe(
  map(data => {
    if(url === 'one') {
      return data[0];
    } else {
      return data[1];
    }
  })
).subscribe(e => console.log(e))

This is not the best solution for your problem but it can be useful sometimes.

Otherwise, you can use iif and you can use like this:

result$ = iif(() => url === "one", one$, two$);