takeUntil 操作符官方给出的定义如下:

Emits the values emitted by the source Observable until a notifier Observable emits a value.

发出由源可观测值发出的值,直到第二个 Observable notifier 发出另一个值,然后结束。

用法

1
2
3
4
5
6
7
8
9
10
11
12
13
takeUntil<T>(notifer: Observable<any>): MonoTypeOperatorFunction<T>


import { fromEvent, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

const source$ = interval(1000);
const click$ = fromEvent(document, 'click);

const result$ = source$.pipe(takeUntil(click$));

result$.subscribe(n => console.log(n));

实现setTimeout功能

1
2
3
4
5
6
7
8

import { timer, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

const timeOut$ = timer(0, 1000)

timeOut$.pipe(takeUntil(timer(5001)))
.subscribe(x => console.log('timeOut$', x));

其他类似的操作符: