Skip to content
Snippets Groups Projects
atlasViewer.workerService.service.ts 1.03 KiB
Newer Older
import { Injectable } from "@angular/core";
import { fromEvent } from "rxjs";
import { filter, take } from "rxjs/operators";
Xiao Gui's avatar
Xiao Gui committed
import { getUuid } from "src/util/fn";
/* telling webpack to pack the worker file */
Xiao Gui's avatar
Xiao Gui committed
import '../../worker/worker.js'
import '../../worker/worker-plotly.js'
/**
 * export the worker, so that services that does not require dependency injection can import the worker
 */
export const worker = new Worker('worker.js')

interface IWorkerMessage {
  method: string
  param: any
}

Xiao Gui's avatar
Xiao Gui committed
  providedIn: 'root',
Xiao Gui's avatar
Xiao Gui committed
export class AtlasWorkerService {
  public worker = worker

  async sendMessage(data: IWorkerMessage){

Xiao Gui's avatar
Xiao Gui committed
    const newUuid = getUuid()
    this.worker.postMessage({
      id: newUuid,
      ...data
    })
    const message = await fromEvent(this.worker, 'message').pipe(
      filter((message: MessageEvent) => message.data.id && message.data.id === newUuid),
      take(1)
    ).toPromise()
    
    const { data: returnData } = message as MessageEvent
    const { id, ...rest } = returnData
    return rest
  }
Xiao Gui's avatar
Xiao Gui committed
}