[RxJS] Combination operators: concat, startWith

Some Observables may complete, and we may want to append another Observable to the one which just completed. This lesson teaches you how to use the concat() operator for either appending or prepending, and how the shortcut operator startWith() is an easy way of prepending values to an Observable.

 

 concat(observalbe): wait until the first observalbe complete than append the scond observable result. 
var foo = Rx.Observable.interval(100).take(7);
var more = Rx.Observable.of(10,11,12,13,14);

/*
--0--1--2--3--4--5--6--7-...
    take(7)
                     (10,11,12,13,14|)       (more)
--0--1--2--3--4--5--6|                       (foo)
   concat
--0--1--2--3--4--5--6|(10,11,12,13,14)|
*/

var bar = foo.concat(more);

bar.subscribe(
  function (x) { console.log('next ' + x); },
  function (err) { console.log('error ' + err); },
  function () { console.log('done'); },
);

  /*
  "next 0"
"next 1"
"next 2"
"next 3"
"next 4"
"next 5"
"next 6"
"next 10"
"next 11"
"next 12"
"next 13"
"next 14"
"done"
  */

 

Observable.concat(first$, second$): static way to concat:

var foo = Rx.Observable.interval(100).take(7);
var more = Rx.Observable.of(10,11,12,13,14);

/*
--0--1--2--3--4--5--6--7-...
    take(7)
                     (10,11,12,13,14|)       (more)
--0--1--2--3--4--5--6|                       (foo)
   concat
--0--1--2--3--4--5--6|(10,11,12,13,14)|
*/

var bar = Rx.Observable.concat(foo, more);

bar.subscribe(
  function (x) { console.log('next ' + x); },
  function (err) { console.log('error ' + err); },
  function () { console.log('done'); },
);

The code return the same result as the code showing before.

 

startWith(value):

var foo = Rx.Observable.interval(100).take(7);


/*
--0--1--2--3--4--5--6--7-...
    take(7)
--0--1--2--3--4--5--6|                       (foo)
   startWith('more')
('more')--0--1--2--3--4--5--6|
*/

var bar = foo.startWith('more');

bar.subscribe(
  function (x) { console.log('next ' + x); },
  function (err) { console.log('error ' + err); },
  function () { console.log('done'); },
);

  /*
"next more"
"next 0"
"next 1"
"next 2"
"next 3"
"next 4"
"next 5"
"next 6"
"done"
  */

 

转载于:https://www.cnblogs.com/Answer1215/p/5528430.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值