2

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?

3
  • .do is for when you don't want to return something and change the value of the stream. Commented Dec 11, 2017 at 21:14
  • @jonsharpe sorry made a mistake in the sample code, I actually meant to use map Commented Dec 12, 2017 at 1:42
  • Checkout this entire article on conditional work in RxJS blog.strongbrew.io/rxjs-patterns-conditionally-executing-work Commented Feb 22, 2019 at 8:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.