0
votes

I have an observable, to which I subscribe and I do some operations on the result value (a reduce() and a map()).

But inside that observable I would like to call another observable that just returns a number, and I need that number in my map().

Here an example:

this.getYearlyDataByIdAndYear(292, 2019).subscribe(result = > {
        let ferienSaldo: FerienSaldo;
        this.getVacationsYearlyDataByIdAndYear(292, 2019).subscribe(result = > {
            // this is my inner observable and I need to save this result, and use it below!
            ferienSaldo = result;
        });
        this.yearlyOverview = result.reduce < Array < YearlyOverview >> ((prev, current, i, all) = > {
                // some code that is not important
                let overviewVar: YearlyOverview = {
                    saldo: ferienSaldo.value
                };
                prev.push(newTLOverview);
            }
            return prev;
        }, new Array < YearlyOverview > ())
});

basically as you can see, inside my initial Observable, I will need the value from the inner one, and I will copy that value inside my reduce() to assign it to a new object I'm creating!

The issue with my code is, the "let ferienSaldo" variable cannot be accessed inside the second observable, and besides that I'm sure there is a better way to combine this!

1

1 Answers

1
votes

It looks like the two calls don't depend on each other, so you can run them in parallel in a forkJoin

forkJoin([
  this.getYearlyDataByIdAndYear(292, 2019).pipe(
    tap(result => this.result1 = result)
  ),
  this.getVacationsYearlyDataByIdAndYear(292, 2019).pipe(
    tap(result => this.result2 = result)
  )
]).subscribe(() => {
  // process this.result1 and this.result2
  // TODO: more meaningful property names
});

Edit:

I used tap because I like to keep my subscribe body clean. You can also return the results in an array to subscribe:

forkJoin([
  this.getYearlyDataByIdAndYear(292, 2019),
  this.getVacationsYearlyDataByIdAndYear(292, 2019)
]).subscribe(result => {
  // process result[0] and result[1]
});

The second option looks cleaner in a trivial example like this, but I find it's annoying to couple your subscribe body to the array indices - especially when you make changes.