Rxjs Custom Subject完成并处置工人

时间:2017-10-10 09:08:01

标签: rxjs web-worker

我想知道是否存在更好的完成工作主题的方法。为此,在所有任务运行时完成。

以下是代码:

export class WorkerSubject<T> extends Subject<T> {

  protected worker: Worker;

  protected jobs = 0;

  protected finish = false;

  constructor(callback: Function, async = false) {
    super();
    this.worker =
      async ? createWorkerPostMessage(callback) : createStaticWorker(callback);
    this.worker.onmessage = e => {
      this.jobs--;
      super.next(e.data);
      if (this.jobs === 0 && this.finish) {
        super.complete();
        this.worker.terminate();
      }
    };
    this.worker.onerror = e => {
      super.error(e);
      this.worker.terminate();
    };
  }

  next(value: any): void {
    if (this.finish) {
       throw new Error('WorkerSubject complete, no more values can be emited.')
    }
    this.jobs++;
    this.worker.postMessage(value);
  }

  complete() {
    this.finish = true;
  }
}

有什么想法改善这个吗?

0 个答案:

没有答案