from

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

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


:bulb: For arrays and iterables, all contained values will be emitted as a
sequence!

:bulb: This operator can also be used to emit a string as a sequence of
characters!


from - 图3

Examples

Example 1: Observable from array

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. //emit array as a sequence of values
  3. const arraySource = from([1, 2, 3, 4, 5]);
  4. //output: 1,2,3,4,5
  5. const subscribe = arraySource.subscribe(val => console.log(val));
Example 2: Observable from promise

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. //emit result of promise
  3. const promiseSource = from(new Promise(resolve => resolve('Hello World!')));
  4. //output: 'Hello World'
  5. const subscribe = promiseSource.subscribe(val => console.log(val));
Example 3: Observable from collection

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. //works on js collections
  3. const map = new Map();
  4. map.set(1, 'Hi');
  5. map.set(2, 'Bye');
  6. const mapSource = from(map);
  7. //output: [1, 'Hi'], [2, 'Bye']
  8. const subscribe = mapSource.subscribe(val => console.log(val));
Example 4: Observable from string

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. //emit string as a sequence
  3. const source = from('Hello World');
  4. //output: 'H','e','l','l','o',' ','W','o','r','l','d'
  5. const subscribe = source.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/from.ts