RxJS Mastery – #10 from

The RxJS from operator creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.

RxJS from explained 🎓

The from operator takes almost anything and returns an Observable. The array’s element are emitted as single values:

from([1,2,3]).subscribe({ next: console.log });
// 1, 2, 3

A infinite iterable form a generator function can also be transformed to an Observable:

function* generateDoubles(seed) {
    let i = seed;
    while (true) {
        yield i;
        i = 2 * i; // double it
    }
}

const iterator = generateDoubles(2);

from(iterator).pipe(
    take(10)
).subscribe({ next: console.log });

// 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024

What problems does the RxJS from operator solve? 🚧

The RxJS from operator is usually applied if you need to create an Observable out of pure JavaScript types.

How to test the from operator🚦

Well, no specialties here. We just use marbles testing. Below test again demonstrates clearly that the values are emitted at the same time. The Observable also completes after all values from an array have been emitted (indicated by the pipe in the marble diagram).

it('should marble test', () => {
    testScheduler.run((helpers) => {
        const { expectObservable } = helpers;

        const result$ = from([1,2,3]);

        expectObservable(result$).toBe('(abc|)', {a: 1, b: 2, c: 3});
    });
});

Exercise for the from operator 💪

Given an input text output each character separately.