Learn RxJS
Search…
from
``# from

signature: from(ish: ObservableInput, mapFn: function, thisArg: any, scheduler: Scheduler): Observable

Turn an array, promise, or iterable into an observable.

πŸ’‘ This operator can be used to convert a promise to an observable!
πŸ’‘ For arrays and iterables, all contained values will be emitted as a sequence!
πŸ’‘ This operator can also be used to emit a string as a sequence of characters!
​​
​
​

Examples

Example 1: Observable from array
1
// RxJS v6+
2
import { from } from 'rxjs';
3
​
4
//emit array as a sequence of values
5
const arraySource = from([1, 2, 3, 4, 5]);
6
//output: 1,2,3,4,5
7
const subscribe = arraySource.subscribe(val => console.log(val));
Copied!
Example 2: Observable from promise
1
// RxJS v6+
2
import { from } from 'rxjs';
3
​
4
//emit result of promise
5
const promiseSource = from(new Promise(resolve => resolve('Hello World!')));
6
//output: 'Hello World'
7
const subscribe = promiseSource.subscribe(val => console.log(val));
Copied!
Example 3: Observable from collection
1
// RxJS v6+
2
import { from } from 'rxjs';
3
​
4
//works on js collections
5
const map = new Map();
6
map.set(1, 'Hi');
7
map.set(2, 'Bye');
8
​
9
const mapSource = from(map);
10
//output: [1, 'Hi'], [2, 'Bye']
11
const subscribe = mapSource.subscribe(val => console.log(val));
Copied!
Example 4: Observable from string
1
// RxJS v6+
2
import { from } from 'rxjs';
3
​
4
//emit string as a sequence
5
const source = from('Hello World');
6
//output: 'H','e','l','l','o',' ','W','o','r','l','d'
7
const subscribe = source.subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 9mo ago