sample

signature: sample(sampler: Observable): Observable

Sample from source when provided observable emits.

sample - 图1

Examples

Example 1: Sample source every 2 seconds

( jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { sample } 'rxjs/operators';
  3. //emit value every 1s
  4. const source = interval(1000);
  5. //sample last emitted value from source every 2s
  6. const example = source.sample.pipe(interval(2000));
  7. //output: 2..4..6..8..
  8. const subscribe = example.subscribe(val => console.log(val));
Example 2: Sample source when interval emits

( 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. //emit 'Joe', 'Frank' and 'Bob' in sequence
  7. from(['Joe', 'Frank', 'Bob']),
  8. //emit value every 2s
  9. interval(2000)
  10. );
  11. //sample last emitted value from source every 2.5s
  12. const example = source.pipe(sample(interval(2500)));
  13. //output: ["Joe", 0]...["Frank", 1]...........
  14. const subscribe = example.subscribe(val => console.log(val));
Example 3: Distinguish between drag and click

From Stack Overflow By
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. })

Additional Resources


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