[RxJS] Use takeUntil instead of manually unsubscribing from Observables
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[RxJS] Use takeUntil instead of manually unsubscribing from Observables相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
RxJS 迁移 5 到 6 - 使用 TakeUntil 取消订阅
[RxJS] Stopping a Stream with TakeUntil
Rxjs【take, first, takeUntil, concatAll】