Answer the question
In order to leave comments, you need to log in
How to use Web Worker on Angular + RxJs?
I would like to perform certain actions in a separate thread (requests to the server and large calculations).
How to do it concisely on Angular + RxJs subscriptions?
If there is a doSomething(param1) function and I need to run it in a web worker and get a response, then send it to the service.
How then to structure if there are a lot of functions and if they are on subscriptions?
Answer the question
In order to leave comments, you need to log in
I do not pretend to be the most correct approach.
How it happened for me
In the service, in the desired method, you connect the web-worker
posts: string = 'https://jsonplaceholder.typicode.com/posts';
submit() {
if (typeof Worker !== 'undefined') {
let input$: Observable<string> = of(this.posts);
fromWorker<string, string>(
() => new Worker(new URL(`./demo.worker`, import.meta.url)),
input$
).subscribe((post) => {
console.log(`Got from worker`, post);
});
} else {
console.log('smth wrong');
}
}
import { DoWork, runWorker } from 'observable-webworker';
import { Observable } from 'rxjs';
import { delay, switchMap } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
export class HelloWorker implements DoWork<any, any> {
public work(input$: Observable<any>): Observable<any> {
return this.getPosts(input$)
}
getPosts(input$: Observable<any>){
return input$.pipe(
delay(1000),
switchMap((i) => ajax.getJSON(i))
);
}
}
runWorker(HelloWorker);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question