from

function stable

Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.

from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T>

Parameters

input

Type: ObservableInput.

scheduler

Optional. Default is undefined.

Type: SchedulerLike.

Returns

Observable<T>:

Description

Converts almost anything to an Observable.

from marble diagram

from converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an iterable object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be converted through this operator.

Examples

Converts an array to an Observable

import { from } from 'rxjs';

const array = [10, 20, 30];
const result = from(array);

result.subscribe(x => console.log(x));

// Logs:
// 10
// 20
// 30

Convert an infinite iterable (from a generator) to an Observable

import { from } from 'rxjs';
import { take } from 'rxjs/operators';

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

const iterator = generateDoubles(3);
const result = from(iterator).pipe(take(10));

result.subscribe(x => console.log(x));

// Logs:
// 3
// 6
// 12
// 24
// 48
// 96
// 192
// 384
// 768
// 1536

With async scheduler

import { from, asyncScheduler } from 'rxjs';

console.log('start');

const array = [10, 20, 30];
const result = from(array, asyncScheduler);

result.subscribe(x => console.log(x));

console.log('end');

// Logs:
// start
// end
// 10
// 20
// 30

See Also

© 2015–2021 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/index/function/from