首页 > Web开发 > 详细

[RxJS] Starting a Stream with SwitchMap & switchMapTo

时间:2016-03-08 07:03:03      阅读:271      评论:0      收藏:0      [点我收藏+]

From an event map to another event we can use switchMap(), switchMap() accept an function which return an obervable.

 

The following code: When you click the button, it will start a interval to console out the count...

const Observable = Rx.Observable;

const startButton = document.querySelector(‘#start‘);


const start$ = Rx.Observable.fromEvent(startButton, ‘click‘);
const interval$ = Observable.interval(400);

const startInterval$ = start$.switchMap( () => {
  return interval$;
});

startInterval$.subscribe( (x) => {
   console.log(x);
});

So the start$ switch map to a interval$ to avoid writting the nested subscribe function.

 

switchMap() actually is pretty useful when dealing with http event stream, it can help to cancel the previous http call.

 

switchMapTo(): which accept an observable:

/*
const startInterval$ = start$.switchMap( () => {
  return interval$;
});*/

const startInterval$ = start$.switchMapTo( interval$ );

Tow pieces of code, works the same way.

[RxJS] Starting a Stream with SwitchMap & switchMapTo

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

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