Learn RxJS
Search…
sample

signature: sample(sampler: Observable): Observable

Sample from source when provided observable emits.

Examples

Example 1: Sample source every 2 seconds
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { sample } from 'rxjs/operators';
4
5
//emit value every 1s
6
const source = interval(1000);
7
//sample last emitted value from source every 2s
8
const example = source.pipe(sample(interval(2000)));
9
//output: 2..4..6..8..
10
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: Sample source when interval emits
1
// RxJS v6+
2
import { interval, zip, from } from 'rxjs';
3
import { sample } from 'rxjs/operators';
4
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));
Copied!
Example 3: Distinguish between drag and click
1
// RxJS v6+
2
import { fromEvent, merge } from 'rxjs';
3
import { sample, mapTo } from 'rxjs/operators';
4
5
const listener = merge(
6
fromEvent(document, 'mousedown').pipe(mapTo(false)),
7
fromEvent(document, 'mousemove').pipe(mapTo(true))
8
)
9
.pipe(sample(fromEvent(document, 'mouseup')))
10
.subscribe(isDragging => {
11
console.log('Were you dragging?', isDragging);
12
});
Copied!

Additional Resources

  • sample 📰 - Official docs
Last modified 1yr ago