RxJS Mastery – #52 throttle

The RxJS throttle and throttleTime operators allow ignoring some values of the source for some time.

RxJS throttle ignores values based on an Observable

The throttle operator expects a parameter durationSelector in the form of:

(value: T) => ObservableInput<any>

This is a function that receives the source value and returns the “duration” Observable. After the first next notification, the values from the source are ignored until the “duration” Observable emits.
In the below case the durationSelector returns an Observable based on the interval operator. Because interval is defined with the duration 2, source values are ignored during 2 time frames each time after the source had the chance to emit a value:

const result$ = interval(1).pipe(
    take(11),
    throttle(() => interval(2))
);

expectObservable(result$).toBe(
    '-a--b--c--d|',
    { a: 0, b: 3, c: 6, d: 9 }
);

RxJS throttleTime throttles based on a duration

The throttleTime operator ignores values during a certain duration passed to the operator. In the following example the throttleTime(3) makes sure the final output has a break of at least 3 time frames after each source value:

const result$ = interval(1).pipe(
    take(10),
    throttleTime(3),
);

expectObservable(result$).toBe(
    '-a---b---c|',
    { a: 0, b: 4, c: 8 }
);

Exercise for the RxJS throttle operator 💪

Take numbers as input from an interval(1). The throttling duration in milliseconds should be equal to the source value if the source value is below 5. If the source value is 5 or higher, the throttling duration should be 5.

const result$ = interval(1).pipe(
    take(11),
    throttle((v: number) => {

    })
);

// can you get this output?
expectObservable(result$).toBe(
    '-ab-c---d--|',
    { a: 0, b: 1, c: 3, d: 7 }
);

This post is part of the RxJS mastery series. As always the code examples can be found on GitHub.