[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"
  */
复制代码

 

posted @   Zhentiw  阅读(338)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示