All files / app-play/src/services library-refresh.ts

95.23% Statements 20/21
75% Branches 3/4
100% Functions 4/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37    42x       2x   2x 2x   2x 2x       4x 4x 4x       28x 29x 29x 29x 29x 29x   2x   29x          
/** Runs background library reads while choosing a chart. An interrupted read starts again after play. */
export class LibraryRefresh {
  private readonly active = new Set<AbortController>();
  private paused: { untilResumed: Promise<void>; resume: () => void } | undefined;
 
  public pause(): void {
    Iif (this.paused !== undefined) return;
    let resume!: () => void;
    const untilResumed = new Promise<void>((resolve) => {
      resume = resolve;
    });
    this.paused = { untilResumed, resume };
    for (const controller of this.active) controller.abort();
  }
 
  public resume(): void {
    const paused = this.paused;
    this.paused = undefined;
    paused?.resume();
  }
 
  public async run<T>(work: (signal: AbortSignal) => Promise<T>): Promise<T> {
    for (;;) {
      while (this.paused !== undefined) await this.paused.untilResumed;
      const controller = new AbortController();
      this.active.add(controller);
      try {
        return await work(controller.signal);
      } catch (error) {
        if (!controller.signal.aborted) throw error;
      } finally {
        this.active.delete(controller);
      }
    }
  }
}