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 { fromWorker } from 'observable-webworker';
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
const input$ = of({ payload: 'Hello from main thread' });
fromWorker<string, string>(() => new Worker('./hello.worker', { type: 'module' }), input$)
.pipe(map(res => res.payload))
.subscribe(message => {
console.log(message);
});
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`,
};
}),
);
}
}
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';
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);