What does from do?
from transforms standard JavaScript data types — such as arrays (including array-like structures), promises, and iterables — into an observable stream of values. It also handles objects that conform to the Observable-like interface, meaning they expose a function under the ES2015 Symbol for Observable (Symbol.observable).
When the input is an array or an iterable, each element is emitted individually as part of the sequence. Strings are treated as iterables as well, so each character becomes a separate emission. To control timing and push values asynchronously, you can pass a scheduler as the second argument. A common scenario is converting a promise into an observable so it fits naturally into an RxJS chain.
The behavior of from can be summarized as follows:
- Instantiate an observable from the given input.
- If the input is an array, iterate through it and emit each element as a standalone value.
- If the input is an iterable, loop over it and emit each element as a standalone value.
- If the input is a promise, wait for resolution and then emit the resolved value. On rejection, an error notification is sent to the observer.
- Once all values have been emitted, a complete notification is sent to the observer.
When to use it
from is a go-to operator when you need to bridge plain JavaScript constructs into the observable world. The example below demonstrates how to convert an array, a promise, and an iterable into observable sequences:
const array = ['array-1', 'array-2', 'array-3'];
const promise = Promise.resolve('promise-1');
const iterable = iterator();
concat(
from(array),
from(iterable),
from(promise)
).subscribe(x => console.log(x));
function* iterator() {
const values = ['iterator-1', 'iterator-2', 'iterator-3'];
for (let i = 0; i < values.length; i++) {
yield values[i];
}
}
For a deeper look at how concat works, refer to this section.
