Last active
July 11, 2016 21:24
-
-
Save rehia/c994f522fec5f607580d0e6b17cb9889 to your computer and use it in GitHub Desktop.
Debounce data based on a key or value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Rx.Observable.prototype.debounceDistinct = function debounceDistinct(delay, keySelector = value => value) { | |
| var source = this; | |
| return Rx.Observable.create((observer) => { | |
| const allKeys = {}; | |
| function reinitDelayFor(key) { | |
| allKeys[key] = false; | |
| setTimeout(() => allKeys[key] = true, delay); | |
| } | |
| return source.subscribe( | |
| function (data) { | |
| try { | |
| const key = keySelector(data); | |
| if (!allKeys.hasOwnProperty(key)) { | |
| reinitDelayFor(key); | |
| } | |
| const shouldPass = allKeys[key]; | |
| if (shouldPass) { | |
| observer.onNext(data); | |
| reinitDelayFor(key); | |
| } | |
| } catch (e) { | |
| observer.onError(e); | |
| } | |
| }, | |
| observer.onError.bind(observer), | |
| observer.onCompleted.bind(observer) | |
| ); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment