RxJS combAll Operator explained

I am trying to understand how the combine all operator works. I am using the following example from the official documentation :

import { take, map, combineAll } from 'rxjs/operators';
import { interval } from 'rxjs';

const source$ = interval(1000).pipe(take(2));

const example$ = source$.pipe(
  map(val =>
    interval(1000).pipe(
      map(i => 'Result (${val}): ${i}'),
      take(5)
    )
  )
);

example$
  .pipe(combineAll())
  .subscribe(console.log);


      

Then the output is:

["Result (0): 0", "Result (1): 0"]
["Result (0): 1", "Result (1): 0"]
["Result (0): 1", "Result (1): 1"]
["Result (0): 2", "Result (1): 1"]
["Result (0): 2", "Result (1): 2"]
["Result (0): 3", "Result (1): 2"]
["Result (0): 3", "Result (1): 3"]
["Result (0): 4", "Result (1): 3"]
["Result (0): 4", "Result (1): 4"]

      

Trying to understand why, I made this simple diagram:

combineAll Scheme

I read from the documentation that every time any of the inner Observable emits a value, that emitted value is merged with the last value of all other inner Observables.

In the above diagram, we can see that the internal values ​​of the Observables emit 10 values ​​over time, so I expected to get an output with 10 values ​​over that time, but it is 9.

Also on the first line of the output:

["Result (0): 0", "Result (1): 0"]) 

      

Does 0 of Result (1): 0 correspond to null? Because the observed "inner 2" has not emitted anything yet?

To finish, here's what I expected as output:

["Result (0): 0", "Result (1): 0"]
["Result (0): 1", "Result (1): 0"]
["Result (0): 1", "Result (1): 0"]
["Result (0): 2", "Result (1): 0"]
["Result (0): 2", "Result (1): 1"]
["Result (0): 3", "Result (1): 1"]
["Result (0): 3", "Result (1): 2"]
["Result (0): 4", "Result (1): 2"]
["Result (0): 4", "Result (1): 3"]
["Result (0): 4", "Result (1): 4"]

      

This is clearly wrong, but I can't find my mistake, can someone please explain?

+4


source to share


1 answer


Please note that combineAll

:

flattens an Observable-of-Observables by applying combineLatest

when the Observable-of-Observables completes.

And this combineLatest

;



will actually wait for all input Observables to emit at least once.

Thus, the first emission from an observable combineAll

that includes the first value of the observable "Inner 1" will not occur until the observable "Inner 2" issues its first value. So there will only be nine outliers, not ten.

+5


source







All Articles