Skip to content

Instantly share code, notes, and snippets.

@deebloo
Last active August 19, 2016 17:24
Show Gist options
  • Save deebloo/83b356d364af2a17a538b379182d8d01 to your computer and use it in GitHub Desktop.
Save deebloo/83b356d364af2a17a538b379182d8d01 to your computer and use it in GitHub Desktop.
A RxJs operator that runs in a new thread. https://github.com/deebloo/rxjs-worker
// https://github.com/deebloo/rxjs-worker
var observable = Observable.of([0, 1, 2, 3, 4]);
observable
.map(function (data) {
return data.concat([5, 6, 7, 8, 9]);
})
.workerMap(function (data) {
return data.concat([10,11,12,13,14]);;
})
.subscribe(function (data) {
console.log(data);
});
// https://github.com/deebloo/rxjs-worker
(function (Rx) {
Rx.Observable.prototype.workerMap = workerMap;
function workerMap(cb) {
var subject = new Rx.Subject();
var worker = _createWorker(cb);
worker.onmessage = function (e) {
subject.next(e.data);
}
this.subscribe(function (value) {
worker.postMessage(value);
});
return subject;
}
function _createWorker(fn) {
var blob = new Blob(
[
'self.cb = ', fn.toString(), ';',
'self.onmessage = function (e) { self.postMessage(self.cb(e.data)) }'
],
{ type: 'text/javascript' }
);
var url = URL.createObjectURL(blob);
return new Worker(url);
}
})(Rx);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment