Skip to content

Instantly share code, notes, and snippets.

@machty machty/some-route.js
Last active Jun 17, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.