π‘ 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!
ββββ
Example 1: Observable from array
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';β//emit array as a sequence of valuesconst arraySource = from([1, 2, 3, 4, 5]);//output: 1,2,3,4,5const subscribe = arraySource.subscribe(val => console.log(val));
Example 2: Observable from promise
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';β//emit result of promiseconst promiseSource = from(new Promise(resolve => resolve('Hello World!')));//output: 'Hello World'const subscribe = promiseSource.subscribe(val => console.log(val));
Example 3: Observable from collection
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';β//works on js collectionsconst map = new Map();map.set(1, 'Hi');map.set(2, 'Bye');βconst mapSource = from(map);//output: [1, 'Hi'], [2, 'Bye']const subscribe = mapSource.subscribe(val => console.log(val));
Example 4: Observable from string
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { from } from 'rxjs';β//emit string as a sequenceconst source = from('Hello World');//output: 'H','e','l','l','o',' ','W','o','r','l','d'const subscribe = source.subscribe(val => console.log(val));
βHTTP Pollingβ
βLockscreenβ
βMemory Gameβ
βProgress Barβ
βfrom π° - Official docs
βCreation operators: from, fromArray, fromPromiseβ
π₯ π΅ - AndrΓ© Staltz
π Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/observable/from.tsβ