Skip to content

Instantly share code, notes, and snippets.

@adrianmcli
Last active January 8, 2017 20:59
Show Gist options
  • Save adrianmcli/97f4f1943a59148707016d4f94898a9e to your computer and use it in GitHub Desktop.
Save adrianmcli/97f4f1943a59148707016d4f94898a9e to your computer and use it in GitHub Desktop.
Tracks how long you've been typing by creating a stream of state change-events and then sampling from that stream every second.
/*** Helper Functions ***/
const showTyping = () => $('.typing').text('User is typing...');
const showIdle = () => $('.typing').text('');
const updateTimer = (x) => $('.timer').text(x);
const handleTypingStateChange = state =>
state === 1 ? showTyping() : showIdle();
/*** Program Logic ***/
const inputEvents$ = Rx.Observable.fromEvent($('#input'), 'input').share();
// streams to indicate when user is typing or has become idle
const typing$ = inputEvents$.mapTo(1);
const isIdle$ = inputEvents$.debounceTime(1000).mapTo(0);
// stream to emit "typing state" change-events
const typingState$ = Rx.Observable.merge(typing$, isIdle$)
.distinctUntilChanged()
.share();
// every second, sample from typingState$
// if user is typing, add 1, otherwise 0
const timer$ = Rx.Observable
.interval(1000)
.withLatestFrom(typingState$, (tick, typingState) => typingState)
.scan((a, b) => a + b, 0)
// subscribe to streams
timer$.subscribe(updateTimer);
typingState$.subscribe(handleTypingStateChange);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment