Загрузка данных


public async reload(tf: Timeframes): Promise<void> {
  const seq = ++this.loadSeq;

  const previousOldestCandle = this.oldestCandle;
  const previousNewestCandle = this.newestCandle;
  const previousLastCandle = this.lastCandleSubject.value;
  const previousIsEndOfData = this.isEndOfData;

  this.isInitializedSubject.next(false);
  this.isLoadingSubject.next(true);

  this.realtimeCache = [];
  this.realtimeBuffer = [];
  this.oldestCandle = null;
  this.newestCandle = null;
  this.isEndOfData = false;

  const task = (async () => {
    try {
      const loaded = (await this.getData(tf, this.symbol)) ?? [];

      if (seq !== this.loadSeq) {
        return;
      }

      const normalized = this.normalizeList(tf, loaded);

      this.oldestCandle = normalized[0] ?? null;
      this.newestCandle = normalized[normalized.length - 1] ?? null;

      this.currentDataSubject.next(normalized);
      this.lastCandleSubject.next(this.newestCandle);

      this.isInitializedSubject.next(true);
      this.flushRealtimeBuffer();
    } catch (error) {
      if (seq !== this.loadSeq) {
        return;
      }

      console.error('[DataSource] Ошибка при загрузке данных:', error);

      this.oldestCandle = previousOldestCandle;
      this.newestCandle = previousNewestCandle;
      this.isEndOfData = previousIsEndOfData;
      this.lastCandleSubject.next(previousLastCandle);
      this.isInitializedSubject.next(true);
    } finally {
      if (seq === this.loadSeq) {
        this.isLoadingSubject.next(false);
      }
    }
  })();

  this.loadingPromise = task;

  task.finally(() => {
    if (this.loadingPromise === task) {
      this.loadingPromise = null;
    }
  });

  await task;
}