RxJS Mastery – #69 toArray

RxJS toArray

RxJS toArray is another utility operator. It emits all the source values as an array once the source completes.

RxJS toArray only works on Observables that complete

As the toArray operator needs to collect all next notifications, it needs to know when the Observable has completed. Only then we can be sure to have caught all values. This also has impact on the timing of the emission of course.

const result$ = cold('abcd|').pipe(
    toArray()
);

expectObservable(result$).toBe(
    '----(r|)',
    {
        r: ['a', 'b', 'c', 'd'],
    }
);

In the above example, the values a, b, c, d are emitted followed by a complete notification. Logically the result$ is emitting once at the time the source has completed.

Exercise for the RxJS toArray operator 💪

Collect 3 values each and emit them as an array repeatedly. You might want to look into the repeat and delay operators.

const result$ = interval(1).pipe(
    // a combination of toArray, take, delay and repeat
);

expectObservable(result$).toBe(
    '----w---x---y---(z|)',
    {
        w: [0, 1, 2],
        x: [0, 1, 2],
        y: [0, 1, 2],
        z: [0, 1, 2],
    }
);

This post is part of the RxJS mastery series. As always the code examples can be found on GitHub.