Just started learning RxJS. Really confused about the combineAll
operator. Would really appreciate an explanation on this example code:
// emit every 1s, take 2
const source$ = interval(1000).pipe(take(2));
// map each emitted value from source to interval observable that takes 5 values
const example$ = source$.pipe(
map(val =>
interval(1000).pipe(
map(i => `Result (${val}): ${i}`),
take(5)
)
)
);
/*
2 values from source will map to 2 (inner) interval observables that emit every 1s.
combineAll uses combineLatest strategy, emitting the last value from each
whenever either observable emits a value
*/
example$
.pipe(combineAll())
/*
output:
["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"]
*/
.subscribe(console.log);
The explanation at learnRxJS and this StackOverflow question are not getting to my head that well.
Areas of ambiguity:
- Why does first output show: ["Result (0): 0", "Result (1): 0"] instead of ["Result (0): 0"]
Because in the First 1000ms, "1" should not have been emitted from the source right?.
- Why are we getting values like: ["Result (0): 1", "Result (1): 0"]
Shoulnt it be.. ["Result (0): 1", "Result (1): 1"]
- According to the definition of combineAll, "Flattens an Observable-of-Observables by applying combineLatest when the Observable-of-Observables completes"
I dont really understand how it "Flattens" and Why we receive the output as individual array in 9 installments.