ObservableWebWorker
Simple API for using web workers with rxjs
Install
Install the npm package: observable-webworker
npm install observable-webworker
yarn add observable-webworker
Usage
Quickstart
import { ObservableWorker, DoWork, GenericWorkerMessage } from 'observable-webworker';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@ObservableWorker()
class HelloWorker implements DoWork<string, string> {
public work(input$: Observable<GenericWorkerMessage<string>>): Observable<GenericWorkerMessage<string>> {
return input$.pipe(
map(message => {
console.log(message);
return {
payload: `Hello from webworker`,
};
}),
);
}
}
import { fromWorker } from 'observable-webworker';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
fromWorker<string, string>(() => new Worker('./hello.worker', { type: 'module' }, of('Hello from main thread')).pipe(
map(res => res.payload),
).subscribe(message => {
console.log(message);
})
Don't like decorators? Don't use em!
If decorators is not something you use regularly and prefer direct functions, simply
use the runWorker
function instead.
import { runWorker, DoWork, GenericWorkerMessage } from 'observable-webworker';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
class HelloWorker implements DoWork<string, string> {
public work(input$: Observable<GenericWorkerMessage<string>>): Observable<GenericWorkerMessage<string>> {
return input$.pipe(
map(message => {
console.log(message);
return {
payload: `Hello from webworker`,
};
}),
);
}
}
runWorker(HelloWorker);