• sample
    • 签名: sample(sampler: Observable): Observable
  • 当提供的 observable 发出时从源 observable 中取样。
    • 示例
      • 示例 1: 每2秒对源 observable 取样
      • 示例 2: 当 interval 发出时对源 observable 取样
      • 示例 3: 区分拖拽和点击
  • 其他资源

    sample

    签名: sample(sampler: Observable): Observable

    当提供的 observable 发出时从源 observable 中取样。

    sample - 图1

    示例

    示例 1: 每2秒对源 observable 取样

    ( jsBin |
    jsFiddle )

    1. import { interval } from 'rxjs/observable/interval';
    2. import { sample } 'rxjs/operators';
    3. // 每1秒发出值
    4. const source = interval(1000);
    5. // 每2秒对源 observable 最新发出的值进行取样
    6. const example = source.sample.pipe(interval(2000));
    7. // 输出: 2..4..6..8..
    8. const subscribe = example.subscribe(val => console.log(val));
    示例 2: 当 interval 发出时对源 observable 取样

    ( jsBin |
    jsFiddle )

    1. import { interval } from 'rxjs/observable/interval';
    2. import { zip } from 'rxjs/observable/zip';
    3. import { from } from 'rxjs/observable/from';
    4. import { sample } 'rxjs/operators';
    5. const source = zip(
    6. // 发出 'Joe', 'Frank' and 'Bob' in sequence
    7. from(['Joe', 'Frank', 'Bob']),
    8. // 每2秒发出值
    9. interval(2000)
    10. );
    11. // 每2.5秒对源 observable 最新发出的值进行取样
    12. const example = source.pipe(sample(interval(2500)));
    13. // 输出: ["Joe", 0]...["Frank", 1]...........
    14. const subscribe = example.subscribe(val => console.log(val));
    示例 3: 区分拖拽和点击

    来源: Stack Overflow
    作者: Dorus

    ( jsBin |
    jsFiddle )

    1. import { fromEvent } from 'rxjs/observable/interval';
    2. import { sample, mapTo } 'rxjs/operators';
    3. const listener = merge(
    4. fromEvent(element, 'mousedown').mapTo(false),
    5. fromEvent(element, 'mousemove').mapTo(true)
    6. )
    7. .pipe(sample(fromEvent(element, 'mouseup')))
    8. .subscribe(isDragging => {
    9. console.log('Were you dragging?', isDragging);
    10. })

    其他资源

    • sample :newspaper: - 官方文档

    :file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/sample.ts