Skip to content

Instantly share code, notes, and snippets.

@rehia
Last active July 11, 2016 21:24
Show Gist options
  • Select an option

  • Save rehia/c994f522fec5f607580d0e6b17cb9889 to your computer and use it in GitHub Desktop.

Select an option

Save rehia/c994f522fec5f607580d0e6b17cb9889 to your computer and use it in GitHub Desktop.
Debounce data based on a key or value
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