Search code examples
angularrxjsreactive-programmingangular2-observables

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?


Solution

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