Skip to content

Instantly share code, notes, and snippets.

@tappleby
Created July 7, 2015 01:52
Show Gist options
  • Save tappleby/342754c4a3fe02d82ec0 to your computer and use it in GitHub Desktop.
Save tappleby/342754c4a3fe02d82ec0 to your computer and use it in GitHub Desktop.
Redux => To web worker
const composedCreateStore = compose(
applyMiddleware(
thunkMiddleware,
dispatchIdMiddleware,
webWorkerMiddleware('/build/worker.js'),
() => promiseMiddleware,
loggerMiddleware
),
createStore
);
const redux = composedCreateStore(reducers, {});
redux.dispatch({
type: "COMPUTE_DATA",
payload: 10,
meta: {
background: true
}
});
// Logged actions:
[
{"type": "COMPUTE_DATA", "payload": 10, "meta": {"background": true, "id": "d1", "backgroundTaskId": "j2", "sequence": "begin"}},
{"type": "COMPUTE_DATA", "payload": 20, "meta": {"background": false, "id": "d1", "backgroundTaskId": "j2", "sequence": "complete"}}
]
import { isFSA } from 'flux-standard-action';
import assign from 'lodash/object/assign'
const dispatch = global.postMessage;
function mergeMeta(action, meta) {
return {...action.meta, ...meta};
}
global.onmessage = function (e) {
if (isFSA(e.data)) {
const action = e.data;
setTimeout(() => dispatch({
...action,
payload: action.payload * 2,
meta: mergeMeta(action, {
sequence: 'complete'
})
}), 5000);
}
};
import uniqueId from 'lodash/utility/uniqueId';
import { isFSA } from 'flux-standard-action';
function mergeMeta(action, meta) {
return {...action.meta, ...meta};
}
export default function webWorkerMiddleware(scriptURL) {
let dispatch = null;
const worker = new Worker(scriptURL);
worker.onmessage = (e) => {
if (dispatch && isFSA(e.data)) {
dispatch(e.data);
}
};
return methods => {
dispatch = methods.dispatch;
return next => action => {
if (!isFSA(action) || !action.meta || !action.meta.background) {
return next(action);
}
const backgroundTaskId = uniqueId('bt');
worker.postMessage({
...action,
meta: mergeMeta(action, {
backgroundTaskId,
background: false
})
});
next({
...action,
meta: mergeMeta(action, {
backgroundTaskId,
sequence: 'begin'
})
});
return backgroundTaskId;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment