Created
November 22, 2019 12:51
-
-
Save MurhafSousli/583d7bc1bec64a80d6951fe1be2ac249 to your computer and use it in GitHub Desktop.
Angular Comlink
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>{{ textStream | async }}</h1> | |
<div> | |
<input type="text" [(ngModel)]="textInput"> | |
<button (click)="run()">Run</button> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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