首页 > Web开发 > 详细

[RxJS] Creation operators: from, fromArray, fromPromise

时间:2016-04-14 01:16:31      阅读:234      评论:0      收藏:0      [点我收藏+]

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"
*/

 

[RxJS] Creation operators: from, fromArray, fromPromise

原文:http://www.cnblogs.com/Answer1215/p/5389527.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!