sample
签名: sample(sampler: Observable): Observable
当提供的 observable 发出时从源 observable 中取样。
示例
示例 1: 每2秒对源 observable 取样
import { interval } from 'rxjs/observable/interval';
import { sample } 'rxjs/operators';
// 每1秒发出值
const source = interval(1000);
// 每2秒对源 observable 最新发出的值进行取样
const example = source.sample.pipe(interval(2000));
// 输出: 2..4..6..8..
const subscribe = example.subscribe(val => console.log(val));
示例 2: 当 interval 发出时对源 observable 取样
import { interval } from 'rxjs/observable/interval';
import { zip } from 'rxjs/observable/zip';
import { from } from 'rxjs/observable/from';
import { sample } 'rxjs/operators';
const source = zip(
// 发出 'Joe', 'Frank' and 'Bob' in sequence
from(['Joe', 'Frank', 'Bob']),
// 每2秒发出值
interval(2000)
);
// 每2.5秒对源 observable 最新发出的值进行取样
const example = source.pipe(sample(interval(2500)));
// 输出: ["Joe", 0]...["Frank", 1]...........
const subscribe = example.subscribe(val => console.log(val));
示例 3: 区分拖拽和点击
来源: Stack Overflow
作者: Dorus
import { fromEvent } from 'rxjs/observable/interval';
import { sample, mapTo } 'rxjs/operators';
const listener = merge(
fromEvent(element, 'mousedown').mapTo(false),
fromEvent(element, 'mousemove').mapTo(true)
)
.pipe(sample(fromEvent(element, 'mouseup')))
.subscribe(isDragging => {
console.log('Were you dragging?', isDragging);
})
其他资源
- sample - 官方文档
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/sample.ts