码迷,mamicode.com
首页 > Web开发 > 详细

[RxJS] Use takeUntil instead of manually unsubscribing from Observables

时间:2017-05-29 14:36:32      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:hand   ted   doc   tor   scribe   --   cti   click   cal   

Manually unsubscribing from subscriptions is safe, but tedious and error-prone. This lesson will teach us about the takeUntil operator and its utility to make unsubscribing automatic.

 

const click$ = Rx.Observable.fromEvent(document, click);

const sub = click$.subscribe(function(ev) {
  console.log(ev.clientX);
});

setTimeout(() => {
  sub.unsubscribe();
}, 2000);

In the code we manully unsubscribe.

 

We can use tha helper methods such as takeUntil, take() help to automatically handle subscritpiton.

const click$ = Rx.Observable
  .fromEvent(document, click);

const four$ = Rx.Observable.interval(4000).take(1);

/*
click$          --c------c---c-c-----c---c---c-
four$           -----------------0|
clickUntilFour$ --c------c---c-c-|
*/

const clickUntilFour$ = click$.takeUntil(four$);

clickUntilFour$.subscribe(function (ev) {
  console.log(ev.clientX);
});

 

[RxJS] Use takeUntil instead of manually unsubscribing from Observables

标签:hand   ted   doc   tor   scribe   --   cti   click   cal   

原文地址:http://www.cnblogs.com/Answer1215/p/6917947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!