Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 602
Martin Nuc Avatar asked Mar 08 '23 06:03

Martin Nuc


2 Answers

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,...).

like image 135
Milad Avatar answered Mar 21 '23 03:03

Milad


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.

like image 22
Mehdi Benmoha Avatar answered Mar 21 '23 04:03

Mehdi Benmoha