How to throttle a stream to get values as early as possible, while getting at most one value every 500ms #6392
-
Let's say I have a stream of events; I want to get the first one immediately, and after get at most one every 500ms. An ugly implementation that seems to work is: let lastTime = 0;
myObserver$
.pipe(
debounce(() =>
timer(Math.max(0, lastTime + 500 - new Date().getTime())),
),
tap(() => {
lastTime = new Date().getTime();
}),
... But of course it's very ugly. throttleTime(500, asyncScheduler, {leading: true, trailing: true}) almost works. But if I get events at times Is there a prettier way than manually keeping track of |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 8 replies
-
When I was going through the issues, a few weeks ago, |
Beta Was this translation helpful? Give feedback.
-
If I understood the problem correctly, I think that another way to create an operator that behaves like that would be something like: export const customThrottle = <T>(time: number): MonoTypeOperatorFunction<T> =>
connect((hotSource$) =>
concat(
hotSource$.pipe(take(1)),
hotSource$.pipe(
auditTime(time),
takeUntil(hotSource$.pipe(switchMapTo(timer(time)))),
),
).pipe(repeat()),
) If you are using RxJS 6, then replace |
Beta Was this translation helpful? Give feedback.
-
The behavior of throttleTime changed in rxjs 7 so it should now work as you expect, if I understand correctly. It will now ensure the spacing between throttles is always at least the throttled amount. I've described the change with a passing test on Stackoverflow: |
Beta Was this translation helpful? Give feedback.
The behavior of throttleTime changed in rxjs 7 so it should now work as you expect, if I understand correctly. It will now ensure the spacing between throttles is always at least the throttled amount.
I've described the change with a passing test on Stackoverflow:
https://stackoverflow.com/questions/57059666/how-does-throttletime-operators-config-parameter-work-throttleconfig/67701965#67701965