欢迎各位兄弟 发布技术文章
这里的技术是共享的
take(count: number): Observable
take
?当只对开头的一组值感兴趣时,你想要的便是 take
操作符。也许你想看看当用户第一次进入页面时,用户首先点击的是什么,你想要订阅点击事件并只取首个值。举例来说,你想要观看赛跑,但其实你只对首先冲过终点的人感兴趣。此操作符很清晰明了,你想要取开头n个值。
如果想基于某个逻辑或另一个 observable 来取任意数量的值,你可以 takeUntil 或 takeWhile!
take
与 skip
是相反的,它接收起始的N个值,而 skip
会跳过起始的N个值。
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { of } from 'rxjs';
import { take } from 'rxjs/operators';
// 发出 1,2,3,4,5
const source = of(1, 2, 3, 4, 5);
// 取第一个发出的值然后完成
const example = source.pipe(take(1));
// 输出: 1
const subscribe = example.subscribe(val => console.log(val));
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
// 每1秒发出值
const interval$ = interval(1000);
// 取前5个发出的值
const example = interval$.pipe(take(5));
// 输出: 0,1,2,3,4
const subscribe = example.subscribe(val => console.log(val));
(StackBlitz | jsFiddle)
<div id="locationDisplay">
Where would you click first?
</div>
// RxJS v6+
import { fromEvent } from 'rxjs';
import { take, tap } from 'rxjs/operators';
const oneClickEvent = fromEvent(document, 'click').pipe(
take(1),
tap(v => {
document.getElementById(
'locationDisplay'
).innerHTML = `Your first click was on location ${v.screenX}:${v.screenY}`;
})
);
const subscribe = oneClickEvent.subscribe();
take - 官方文档
过滤操作符: take, first, skip - André Staltz
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/take.ts
来自 https://rxjs-cn.github.io/learn-rxjs-operators/operators/filtering/take.html