Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rx debounce operator with first and last

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.

like image 574
George Mavritsakis Avatar asked Mar 12 '16 11:03

George Mavritsakis


1 Answers

To get the the first debounced element, you can use throttle. To get the last, you can use debounce. You however should make sure that the source you are debouncing or throttling is a hot source as you will apply both operators to the same source. Then if you want both elements in the same observable, then you can just merge the throttled and debounced streams.

For example, calling source$ your source observable:

firstAndLast$ = Rx.Observable.merge(source$.debounce(Xms), source$.throttle(Xms))

This should issue the first item and the last item of a burst in the same stream. Note that in the edge case that this is not a burst but a single value that is occuring within the Xms time period, you might have twice the same value, one at the beginning of the period, and one at the end. A way to protect against that, if that makes sense is to use distinctUntilChanged, so this becomes:

firstAndLast$ = Rx.Observable.merge(source$.debounce(Xms), source$.throttle(Xms)).distinctUntilChanged()
like image 86
user3743222 Avatar answered Sep 19 '22 04:09

user3743222