[RxJS] Starting a Stream with SwitchMap & switchMapTo

本文介绍如何利用RxJS中的switchMap操作符简化事件流处理。通过示例代码展示了当点击按钮时启动定时任务输出计数的过程,并比较了switchMap与switchMapTo的区别。此外还介绍了在HTTP事件流中使用switchMap取消前一个HTTP请求的方法。

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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值