Skip to content

Instantly share code, notes, and snippets.

@MurhafSousli
Created November 22, 2019 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MurhafSousli/583d7bc1bec64a80d6951fe1be2ac249 to your computer and use it in GitHub Desktop.
Save MurhafSousli/583d7bc1bec64a80d6951fe1be2ac249 to your computer and use it in GitHub Desktop.
Angular Comlink
<h1>{{ textStream | async }}</h1>
<div>
<input type="text" [(ngModel)]="textInput">
<button (click)="run()">Run</button>
</div>
import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { releaseProxy, Remote, wrap } from 'comlink';
declare type TestWorker = (text: string) => string;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnInit, OnDestroy {
// Updates the UI when text has changed
textStream = new BehaviorSubject('Text');
// Input text
textInput = 'Hello World';
// Web worker proxy
proxy: Remote<TestWorker>;
ngOnInit() {
// Load the worker
const worker = new Worker('./app.worker', { type: 'module' });
// Wrap the worker in a proxy
this.proxy = wrap<TestWorker>(worker);
}
ngOnDestroy() {
// Detach the proxy (Unsubscribe from the worker)
this.proxy[releaseProxy]();
}
async run() {
// Use the proxy to call the web worker function
const text = await this.proxy(this.textInput);
this.textStream.next(text);
}
}
/// <reference lib="webworker" />
import * as Comlink from 'comlink';
export function test(text: string): string {
return `"${text}" from worker`;
}
Comlink.expose(test);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment