Lessons7. of(array) vs from(array)
Lessons · 07
7. of(array) vs from(array)
Same array — different streams
This is a classic trap nearly every RxJS beginner falls into. Let's pass the very same array to of and to from and see what comes out.
of, with or without the brackets
of([1, 2, 3])
// next([1, 2, 3]) → complete()
// one signal carrying the whole array
from([1, 2, 3])
// next(1) → next(2) → next(3) → complete()
// three separate signals
Remember the rule: of sends its argument "as is", without taking it apart. from unpacks the input structure (an array, Promise, or iterable) into elements.
A tell-tale sign of the mistake
If your subscription suddenly hands you an array where you expected individual elements, you almost certainly called of(array) instead of from(array).
Your task
- Replace
Rx.EMPTYonwholeArray$withof(items). The first subscriber gets one whole array and joins it with'-'. - Replace
Rx.EMPTYonitems$withfrom(items). The second subscriber gets three separate values. - Expected output:
Whole: x-y-zItem: xItem: yItem: z
Solution spoiler · click to reveal
const { of, from } = Rx;
const items = ['x', 'y', 'z'];
const wholeArray$ = of(items);
const items$ = from(items);
wholeArray$.subscribe(value => {
console.log('Whole: ' + value.join('-'));
});
items$.subscribe(value => {
console.log('Item: ' + value);
}); script.ts
CONSOLE · Console output
Hit Run to see the result...