Skip to content

Instantly share code, notes, and snippets.

@machty
Last active June 17, 2018 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save machty/121e4d4ec541156c59747ac21540e4c3 to your computer and use it in GitHub Desktop.
Save machty/121e4d4ec541156c59747ac21540e4c3 to your computer and use it in GitHub Desktop.
I have a user-activity service that exposes some observables that monitor the user clicking/tapping around and expose some convenience methods for generating new observables, which allows for the flexibility of consumers specifying different activity times. Refactoring this to use tasks vs observables points out a few awkward cases that could be…
import { inject as service } from '@ember/service';
import Route from '@ember/routing/route';
const DEFAULT_INACTIVITY_TIMEOUT_MS = 10 * 60 * 1000
export default Route.extend({
session: service(),
userActivity: service(),
notifications: service(),
logoutTimeoutSubscription: null,
activate() {
this.logoutTimeoutSubscription =
this.get('userActivity')
.makeActivityObservable(DEFAULT_INACTIVITY_TIMEOUT_MS)
.filter(v => !v)
.subscribe(() => {
this.transitionTo('pin')
});
},
deactivate() {
this.logoutTimeoutSubscription.dispose()
},
});
import { on } from '@ember/object/evented';
import { computed } from '@ember/object';
import Service from '@ember/service';
const INTERACTION_RESUME_TIMEOUT = 40000;
const Rx = window.Rx;
const { timer } = Rx.Observable;
export default Service.extend({
lastInteractionAt: 0,
interactions: computed(function() {
return Rx.Observable.fromEvent(document, 'click').publish().refCount();
}),
makeActivityObservable(timeout) {
return this.get('interactions').flatMapLatest(() => {
return timer(timeout).map(() => false).startWith(true);
}).distinctUntilChanged();
},
watchForActivity: on('init', function() {
this.get('interactions').subscribe(() => {
this.set('lastInteractionAt', +new Date());
});
}),
interactionsResumed: computed(function() {
return this.get('interactions')
.makeActivityObservable(INTERACTION_RESUME_TIMEOUT + 10)
.filter(v => v);
}),
getHasRecentlyInteracted() {
let timeSinceLastUserInteraction = +new Date() - this.get('lastInteractionAt');
return timeSinceLastUserInteraction < INTERACTION_RESUME_TIMEOUT;
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment