R
R
Roman Rakzin2022-01-03 13:34:47
Angular
Roman Rakzin, 2022-01-03 13:34:47

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

1 answer(s)
L
Lan_ser, 2022-01-25
@Lan_ser

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');
      
    }
  }

web worker
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);

For each task, I create a new web worker. But I think there is a way to avoid it.
Hope this helps

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question