Rx debounce operator with first and last

Viewed 4955

Is there any combination of rx operators so as to get the first and last debounced event?

This is going to be used in master detail scenarios (or even seach scenarios) where we want immediate loading of first selected item and the last after user stops changing selection.

This would prevent the debounce time to be injected when the user navigates slowly but also prevent bursts of changes.

If debounce operator had an option "immediate" like underscore.js debounce functoin then a merge of the 2 versions of debounce operator would generate the needed result.

3 Answers

Just combining the throttle and debounce as suggested in the previous answer was not enough for me because it periodically emits new events when the throttle time runs out.

const debounced$ = source$.debounceTime(time)
return source$.throttleTime(time)
  .merge(debounced$).distinctUntilChanged()

With a time=30 you would get:

-a-a-a-a-a-a----
-a---a---a----a-

To only get the first and last event with a minimum time in between I used:

const debounced$ = source$.debounceTime(time)
return source$.throttle(() => debounced)
  .merge(debounced$).distinctUntilChanged()

Which results in:

-a-a-a-a-a-a----
-a------------a-
Related