Skip to content

Instantly share code, notes, and snippets.

@iansinnott
Forked from BerkeleyTrue/login-expire.js
Last active September 14, 2016 07:08
Show Gist options
  • Save iansinnott/79c696cdc217510e8f066a4fc41776f6 to your computer and use it in GitHub Desktop.
Save iansinnott/79c696cdc217510e8f066a4fc41776f6 to your computer and use it in GitHub Desktop.
import ms from 'ms';
import Rx from 'rxjs/Rx';
const clicks$ = Rx.Observable.fromEvent(document.body, 'click');
const createActionStream = () => Rx.Observable.merge(
Rx.Observable.of({ type: 'warning' }).delay(ms('14m')),
Rx.Observable.of({ type: 'logOut' }).delay(ms('15m'))
);
// We map our stream of clicks into a stream of 2 actions happening at 14 and 15
// minutes from the time of the click. Since we are using switchMap (as opposed
// to simply flatMap) we _only_ operate on the latest action stream. Meaning
// every click effectively discards all other delayed actions. The result is
// that every click resets both delays so that the first will fire only after 14
// minutes of inactivity (no clicks).
//
// NOTE: If we were using redux-observable or anything similar which handled the
// subscription for us we could use `.do` instead.
const inactivity$ = clicks$
.startWith(null)
.switchMap(createActionStream) // AKA flatMapLatest
.subscribe(handleInactivity); // See NOTE
// TODO: This doesn't actually do anything. In the real codebase we would run
// some logic here to switch on x.type and either display a warning message or
// log out. Since we've used valid Redux actions would could dispatch them
// directly
function handleInactivity(x) {
console.log(x.type);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment