Rxjs distinctUntilChanged with timer

Just append a date property to the previous map output, and compare it in the distinctUntilChanged, and pluck out the date property after :)

fromEvent(document, 'keydown')
    .pipe(
        map(e => ({key: e.key, time: Date.now()})),
        distinctUntilChanged((a, b) => (a.key == b.key) && (a.time > b.time - 500)),
        pluck('key')
    )

skipUntil should do what you are looking for, if I understood right.

This can be an example

const obs = interval(100).pipe(
    tap(d => console.log('data emitted', d)),
    take(10),
);


obs
.pipe(
    skipUntil(interval(500).pipe(take(1)))
)
.subscribe(
    data => console.log('data read in the subscription', data)
)

This is one of the very rare occasions where windowTime is useful. windowTime creates a new Subject after a period of time that is passed further (so called higher-order Observable). Then you can use concatMap to chain it with distinctUntilChanged. This all means you'll create a new distinctUntilChanged every 1s:

const subject = new Subject();

subject
  .pipe(
    windowTime(1000),
    concatMap(obs => obs.pipe(distinctUntilChanged())),
  )
  .subscribe(console.log);

subject.next(1);
subject.next(2);

setTimeout(() => subject.next(2), 1200);

See live demo: https://stackblitz.com/edit/rxjs6-demo-pcmrzz?file=index.ts

Tags:

Rxjs