Skip to content

Instantly share code, notes, and snippets.

@adrianmcli
Last active January 8, 2017 21:01
Show Gist options
  • Save adrianmcli/8ba2008bc5a929d932ab102b30379ae7 to your computer and use it in GitHub Desktop.
Save adrianmcli/8ba2008bc5a929d932ab102b30379ae7 to your computer and use it in GitHub Desktop.
Tracks how long you've been typing by starting a counting stream every time a typing event has been detected.
/*** Helper Functions ***/
const showTyping = () => $('.typing').text('User is typing...');
const showIdle = () => $('.typing').text('');
const updateTimer = (x) => $('.timer').text(x);
/*** Program Logic ***/
// declare shared streams
const inputEvents$ = Rx.Observable.fromEvent($('#input'), 'input').share();
const idle$ = inputEvents$.debounceTime(1000).share();
// intermediate stream for counting until idle
const countUntilIdle$ = Rx.Observable
.interval(1000)
.startWith('start counter') // first tick required so we start watching for idle events right away
.takeUntil(idle$);
// build clock stream
const clock$ = inputEvents$
.exhaustMap(() => countUntilIdle$)
.scan((acc) => acc + 1, 0)
// subscribe to streams
idle$.subscribe(showIdle);
inputEvents$.subscribe(showTyping);
clock$.subscribe(updateTimer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment