cubiclewar
cubiclewar

Reputation: 1579

Angular/Rxjs Conditional nested Observables

I recently converted a function to dynamically retrieve data from disk rather than memory and during the process went from synchronously returning a variable to returning a Observable.

As part of this conversion every dependent function had to be converted to async via Observables and one of these functions performs a nested conditional call that gets the last scenario for a category or if there was no previous scenario for a category generates gets a default scenario:

public generateScenario(category: string, value: number = 1) : Observable<Scenario>
{
    return this.getHistory(category).map(scenario => {
        if(scenario === null)
        {
            return this.defaultService.getDefault(category, value);
        }
        else
        {
            return scenario;
        }
    });
}

Here this.defaultService.getDefault(category, value) returns an Observable which means that when the scenario === null branch is executed generateScenario() returns an Observable>.

How do I flatten this out and avoid returning a nested Observable?

Upvotes: 2

Views: 943

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191799

You can flatten this out with various flattening operators in RxJS such as switch or merge. In this case, switch seems most appropriate:

this.getHistory(category).switchMap(scenario =>
  scenario === null ? this.defaultService.getCategory(category, value)
  : of(scenario)
);

The of is required the function passed to .switchMap must return an Observable to be flattened/unwrapped/etc.

Upvotes: 2

Related Questions