示例工程 25-vue-reactivity-streaming

25-vue-reactivity-streaming/app/src/lib/stream-store.ts

typescript · 2.4 KB

import { markRaw, shallowRef, type ShallowRef } from "vue";
import type { StreamEvent } from "../../shared/ipc";

export type StreamStore = {
  events: ShallowRef<StreamEvent[]>;
  received: ShallowRef<number>;
  flushes: ShallowRef<number>;
  paused: ShallowRef<boolean>;
  pausedCount: ShallowRef<number>;
  pending: ShallowRef<number>;
  dropped: ShallowRef<number>;
  pushBatch: (batch: StreamEvent[]) => void;
  flushNow: () => void;
  setPaused: (value: boolean) => void;
  reset: () => void;
};

export function createStreamStore(capacity = 2000, flushMs = 150): StreamStore {
  const events = shallowRef<StreamEvent[]>([]);
  const received = shallowRef(0);
  const flushes = shallowRef(0);
  const paused = shallowRef(false);
  const pausedCount = shallowRef(0);
  const pending = shallowRef(0);
  const dropped = shallowRef(0);

  let raw: StreamEvent[] = [];
  let timer: ReturnType<typeof setTimeout> | null = null;

  function publish(): void {
    events.value = raw.slice();
    pending.value = 0;
    flushes.value += 1;
  }

  function flushNow(): void {
    if (timer !== null) {
      clearTimeout(timer);
      timer = null;
    }
    publish();
  }

  function schedule(): void {
    if (timer !== null) return;
    timer = setTimeout(() => {
      timer = null;
      publish();
    }, flushMs);
  }

  function pushBatch(batch: StreamEvent[]): void {
    received.value += batch.length;
    if (paused.value) pausedCount.value += batch.length;
    // markRaw 会给对象打标记;不要污染与深响应式车道共享的同一对象。
    for (const event of batch) raw.push(markRaw({ ...event }));
    if (raw.length > capacity) {
      const overflow = raw.length - capacity;
      raw = raw.slice(overflow);
      dropped.value += overflow;
    }
    pending.value = raw.length - events.value.length;
    schedule();
  }

  function setPaused(value: boolean): void {
    paused.value = value;
    if (!value) pausedCount.value = 0;
  }

  function reset(): void {
    if (timer !== null) {
      clearTimeout(timer);
      timer = null;
    }
    raw = [];
    events.value = [];
    received.value = 0;
    flushes.value = 0;
    paused.value = false;
    pausedCount.value = 0;
    pending.value = 0;
    dropped.value = 0;
  }

  return {
    events,
    received,
    flushes,
    paused,
    pausedCount,
    pending,
    dropped,
    pushBatch,
    flushNow,
    setPaused,
    reset,
  };
}