您的位置:首页 > Web前端 > JavaScript

[RxJS] Use takeUntil instead of manually unsubscribing from Observables

2017-05-29 14:07 477 查看
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);
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: