示例工程 25-vue-reactivity-streaming

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

javascript · 2.1 KB

import { markRaw, shallowRef } from "vue";
export function createStreamStore(capacity = 2000, flushMs = 150) {
    const events = shallowRef([]);
    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 = [];
    let timer = null;
    function publish() {
        events.value = raw.slice();
        pending.value = 0;
        flushes.value += 1;
    }
    function flushNow() {
        if (timer !== null) {
            clearTimeout(timer);
            timer = null;
        }
        publish();
    }
    function schedule() {
        if (timer !== null)
            return;
        timer = setTimeout(() => {
            timer = null;
            publish();
        }, flushMs);
    }
    function pushBatch(batch) {
        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) {
        paused.value = value;
        if (!value)
            pausedCount.value = 0;
    }
    function reset() {
        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,
    };
}
//# sourceMappingURL=stream-store.js.map