DEV Community

Deborah Kurata for Angular

Posted on

RxJS Tip: Creation Function: from()

The RxJS from function is a creation function that iterates an object and emits its values.

How Does It Work?

The from creation function can convert many kinds of things to an Observable. It can take in an array, a promise, or other iterable object. It creates an Observable, iterates the provided object emitting its values, and completes.

The Observable created with from is generally synchronous, meaning the values are iterated and emitted, and the Observable completes immediately after it is subscribed.

Alt Text

The above example passes an array of three strings to the from function and subscribes.

The from iterates the array, emitting each of the three array elements which are logged.

How About Some Examples?

This example iterates an array, emitting each of its elements.

// Array: Iterates and emits the elements
from([42, 72, 21]).subscribe(x => console.log(x)); // 42,72,21
Enter fullscreen mode Exit fullscreen mode

The following example iterates the characters of a string.

/ String: Iterates and emits the characters
from('Apple1').subscribe(x => console.log(x)); // A,p,p,l,e,1 
Enter fullscreen mode Exit fullscreen mode

This example emits the result of a promise.

// Promise: Emits the fulfilled result of the promise
const p = new Promise( ( resolve, reject ) => {
  resolve( "Apple1" );
  reject( "Error" );
} );
from(p).subscribe(x => console.log(x)); // Apple1
Enter fullscreen mode Exit fullscreen mode

What Are Some Common Uses?

In addition to converting other structures to Observables, here are some common uses of the from creation function.

Sample code to try out a pipeline of operations when working with an array.

from([1, 2, 3])
Enter fullscreen mode Exit fullscreen mode

User selects items for processing (ids of products in a cart, ids of selected songs for a playlist, etc.), managed as an array.

from([45, 72, 21])
Enter fullscreen mode Exit fullscreen mode

Where's the Code?

Here is a link to sample code demonstrating the from creation function. Feel free to fork it and try it out.

What About the Marble Diagram?

This is the from creation function shown on a marble diagram:

Alt Text

Thanks to @michael_hladky for this marble diagram.

Do you have another common use of from? If so, please leave a comment.


Top comments (0)