sample

signature: sample(sampler: Observable): Observable

Sample from source when provided observable emits.

Examples

Example 1: Sample source every 2 seconds

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { interval } from 'rxjs';
import { sample } from 'rxjs/operators';

//emit value every 1s
const source = interval(1000);
//sample last emitted value from source every 2s
const example = source.pipe(sample(interval(2000)));
//output: 2..4..6..8..
const subscribe = example.subscribe(val => console.log(val));

Example 2: Sample source when interval emits

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { interval, zip, from } from 'rxjs';
import { sample } from 'rxjs/operators';

const source = zip(
  //emit 'Joe', 'Frank' and 'Bob' in sequence
  from(['Joe', 'Frank', 'Bob']),
  //emit value every 2s
  interval(2000)
);
//sample last emitted value from source every 2.5s
const example = source.pipe(sample(interval(2500)));
//output: ["Joe", 0]...["Frank", 1]...........
const subscribe = example.subscribe(val => console.log(val));

Example 3: Distinguish between drag and click

From Stack Overflow By Dorus

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { fromEvent, merge } from 'rxjs';
import { sample, mapTo } from 'rxjs/operators';

const listener = merge(
  fromEvent(document, 'mousedown').pipe(mapTo(false)),
  fromEvent(document, 'mousemove').pipe(mapTo(true))
)
  .pipe(sample(fromEvent(document, 'mouseup')))
  .subscribe(isDragging => {
    console.log('Were you dragging?', isDragging);
  });

Additional Resources

  • sample

    :newspaper: - Official docs

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

Last updated