Skip to content

Instantly share code, notes, and snippets.

@kievsash
Created January 28, 2019 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kievsash/42c1f0d61ea850aa2ea4c39438a4fb70 to your computer and use it in GitHub Desktop.
Save kievsash/42c1f0d61ea850aa2ea4c39438a4fb70 to your computer and use it in GitHub Desktop.
groupBy use-case
let Rx = window['rxjs'];
let {from, of, asyncScheduler} = Rx;
let {mergeMap, filter, delay, groupBy, throttleTime} = Rx.operators;
console.clear();
let throttleSelectiveFilter = (throttleTimeout = 0, selector = (x) => x) => {
return (source) => {
return source.pipe(
groupBy(selector),
mergeMap((group$) => group$.pipe(throttleTime(throttleTimeout)))
)
}
}
let notifications = [
{ userId: 1, name: 'A1', delay: 100 }, // should be shown
{ userId: 1, name: 'A2', delay: 1500 }, // shouldn't be shown
{ userId: 1, name: 'A3', delay: 2500 }, // shouldn't be shown
{ userId: 1, name: 'A4', delay: 3500 }, // should be shown
{ userId: 2, name: 'B1', delay: 200 }, // should be shown
{ userId: 2, name: 'B2', delay: 300 }, // shouldn't be shown
{ userId: 2, name: 'B3', delay: 3500 }, // should be shown
]
let source$ = from(notifications).pipe(
mergeMap((notif) => {
return of(notif).pipe(delay(notif.delay));
}),
)
source$
.pipe(throttleSelectiveFilter(3000, (x) => x.userId))
.subscribe(showNotification);
let container = document.querySelector('.container');
function showNotification(notif) {
const newElem = document.createElement('div');
newElem.classList.add('item');
newElem.innerHTML = notif.name;
container.appendChild(newElem);
setTimeout(() => {newElem.remove()}, 800);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment