The of() operator essentially converted a list of arguments to an Observable. Since arrays are often how we structure list of things in JavaScript, we should have a way of transforming arrays into Observables. This lesson teaches how you can convert from Arrays to Observables, from Promises to Observables, and from Iterators to Observables.
formArray:
var ary = [1,2,3]; var foo = Rx.Observable.fromArray(ary); foo.subscribe(function (x) { console.log('next ' + x); }, function (err) { console.log('error ' + err); }, function () { console.log('done'); }); /* "next 1" "next 2" "next 3" "done" */
fromPromise:
var prom = fetch('https://null.jsbin.com'); var foo = Rx.Observable.fromPromise(prom); foo.subscribe(function (x) { console.log('next ' + x.status); }, function (err) { console.log('error ' + err); }, function () { console.log('done'); }); /* "next 204" "done" */
from:
from() opreator can create observalbes according to what you passed in
=fromArray:
var ary = [1,2,3]; var foo = Rx.Observable.from(ary); foo.subscribe(function (x) { console.log('next ' + x); }, function (err) { console.log('error ' + err); }, function () { console.log('done'); }); /* "next 1" "next 2" "next 3" "done" */
=fromPromiose
var foo = Rx.Observable.from(prom); foo.subscribe(function (x) { console.log('next ' + x.status); }, function (err) { console.log('error ' + err); }, function () { console.log('done'); });
From iterator:
function* generator(){ yield 10; yield 20; yield 30; } var iterator = generator(); var foo = Rx.Observable.from(iterator); foo.subscribe(function (x) { console.log('next ' + x); }, function (err) { console.log('error ' + err); }, function () { console.log('done'); }); /* "next 10" "next 20" "next 30" "done" */