Martin Nuc
Martin Nuc

Reputation: 5774

Difference between sample and throttle in rxjs

I think I don't understand difference between sample and throttle correctly.

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-sample

http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-throttle

They are both used to silence observable. Sample uses notifier to emit values and throttle uses function to determine how long it should ignore values?

Is that correct?

Upvotes: 4

Views: 2256

Answers (2)

Milad
Milad

Reputation: 28610

In below examples :

//emit value every 1 second
const source = Rx.Observable.interval(1000);

Throttle :

//throttle for 2 seconds, emit latest value
const throttle = source.throttle(val => Rx.Observable.interval(2000));
//output: 0...3...6...9
throttle.subscribe(val => console.log(val));

Sample :

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

As you can see, Sample picked up the latest emitted event (0, 2,...), whereas Throttle turned off the stream for 2 seconds and waited for the next one to be emitted ( 0, 3, 6,...).

Upvotes: 4

Mehdi Benmoha
Mehdi Benmoha

Reputation: 3945

Throttle ignores every events in the time interval. So, if your notifier emits an events, all the previous events from the source are ignored (and deleted).

Sample returns the last event since the last sample. So if the notifier emits an event, it will look from the source events the latest one from the last sampling.

Upvotes: 3

Related Questions