Skip to content

Instantly share code, notes, and snippets.

@CharlieHess
Last active September 27, 2017 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CharlieHess/ef60c4c14f04c0e52ab3cd2e58cf765f to your computer and use it in GitHub Desktop.
Save CharlieHess/ef60c4c14f04c0e52ab3cd2e58cf765f to your computer and use it in GitHub Desktop.
An Epic that tallies time spent in workspaces
/**
* Keep a running total of time spent on each workspace and, once the app is quit,
* fire an action that updates the usage property in the store.
*/
const tallyWorkspaceUsageEpic = (action$, store, scheduler) => {
return selectionChangedObservable(action$, store)
.timeInterval(scheduler)
.pairwise()
.reduce(usagePayloadFromIntervals, {})
.map((payload) => ({
type: WORKSPACE.UPDATE_USAGE,
payload
}));
};
/**
* An Observable that emits any time the selected workspace might change.
*/
function selectionChangedObservable(action$, store) {
/**
* We need to terminate the stream when the app is quit, otherwise reduce
* won't kick in.
*/
return action$.ofType(
WORKSPACE.ADDED,
WORKSPACE.REMOVED,
WORKSPACE.SELECTION_CHANGED
)
.takeUntil(action$.ofType(APP.QUIT))
.filter(() => getWorkspacesCount(store) > 1);
}
/**
* An interval pair here represents a workspace changed event. Given a pair like:
*
* [ { value: 'Workspace 1', interval: 5000 } ],
* [ { value: 'Workspace 2', interval: 10000 } ]
*
* The value from the first corresponds to the workspace that was selected, and
* the interval from the second represents the amount of time it was selected for.
*/
function usagePayloadFromIntervals(payload, intervals) {
const [ first, second ] = intervals;
const existingTime = payload[first.value] || 0;
payload[first.value] = existingTime + second.interval;
return payload;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment