DEV Community

Discussion on: Observable Web Workers with Angular (8) - Introduction

Collapse
 
jzabinskidolios profile image
jzabinski-dolios

Just went through this helpful introduction. As of 2022, there seem to be just a few differences to highlight:

  1. ObservableWorker has been deprecated. runWorker is intended to replace it, like this:
import { DoWork, runWorker } from 'observable-webworker';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

export class DemoWorker implements DoWork<string, string> {
  public work(input$: Observable<string>): Observable<string> {
    return input$.pipe(map((data) => `worker response to ${data}`));
  }
}

runWorker(DemoWorker);
Enter fullscreen mode Exit fullscreen mode
  1. If you run this code in a browser, you will probably notice that the worker thread continues to stick around after it has run. This is because the workers are kept as part of the inner workings of fromWorker. It will terminate those workers when the subscription is unsubscribed (not just when the observable emits Complete). So this code:
  runWorker() {
    const input$: Observable<string> = of('hello');

   fromWorker<string, string>(
      () => new Worker(new URL('./app.worker', import.meta.url), { type: 'module' }),
      input$
    ).subscribe((message) => {
      console.log(`Got message`, message);
    });
  }
Enter fullscreen mode Exit fullscreen mode

Should really be this code:

--> subscription = new Subscription();

  runWorker() {
    const input$: Observable<string> = of('hello');

-->     this.subscription.add(fromWorker<string, string>(
      () => new Worker(new URL('./app.worker', import.meta.url), { type: 'module' }),
      input$
    ).subscribe((message) => {
      console.log(`Got message`, message);
-->      this.subscription.unsubscribe();
    })
    );
  }
Enter fullscreen mode Exit fullscreen mode