I am trying to move heavy calculation task or method-calls to separate web workers. I am using URL.createObjectURL(blob) to inject worker code. But from the code, it has to call some other functions which are defined in Typescript (it is hard to put all complex logic in the worker's blob).
let workers = {};
export function mapWorker<T, R>(cb: (value: T) => R, input: any): Observable<R>
{
const subject = new Subject<R>();
let workerString = cb.toString();
let worker: Worker;
if (workers[workerString])
{
worker = workers[workerString];
} else{
worker = createStaticWorker(cb);
workers[workerString] = worker;
}
worker.onmessage = e => subject.next(e.data);
worker.onerror = err => subject.error(err);
worker.postMessage(input);
return subject;
}
export function createStaticWorker(fn: Function): Worker
{
const blob = new Blob(
[ 'self.cb = ', fn.toString(), ';',
'self.onmessage = function (e) { self.postMessage(self.cb(e.data)) }'
], {
type: 'text/javascript'
}
);
const url = URL.createObjectURL(blob);
return new Worker(url);
}
When using it, I did this.
mapWorker(x =>
{
return Helper.AsyncCalc(x as Array<any>);
}, inputs).subscribe(value => this.areas = value);
Then 'Helper.AsyncCalc' was the method defined in Helper.ts which contains majority of the logic. I noted that in run time the 'helper' name has been compiled to different name in JS which led to an error saying that was undefined. Could someone help on this? Is there any way to call Typescript method from that js inline method?
Thanks so much in advance.
Aucun commentaire:
Enregistrer un commentaire