UNPKG

@slan-health/taro-vueuse

Version:

taro vue版本hooks

56 lines (55 loc) 1.8 kB
import { ref, computed, onUnmounted } from "vue"; import { definePlugin } from "../definePlugin.js"; import { refToRaw, isNil } from "../utils/index.js"; import usePageReVisible from "./taro/usePageReVisible.js"; const usePollingPlugin = definePlugin( (queryInstance, { pollingInterval, pollingWhenHidden = false, errorRetryCount = 0 }) => { const pollingTimer = ref(); const { subscribe, visible } = usePageReVisible(); const pollingIntervalRef = computed(() => refToRaw(pollingInterval)); const errorRetryCountRef = computed(() => refToRaw(errorRetryCount)); const unsubscribeList = []; const addUnsubscribeList = (event) => { event && unsubscribeList.push(event); }; const polling = (pollingFunc) => { let timerId; if (!isNil(pollingIntervalRef.value) && pollingIntervalRef.value >= 0) { timerId = setTimeout(pollingFunc, pollingIntervalRef.value); } return () => timerId && clearTimeout(timerId); }; const stopPolling = () => { var _a; unsubscribeList.forEach((unsubscribe) => unsubscribe()); (_a = pollingTimer.value) == null ? void 0 : _a.call(pollingTimer); }; onUnmounted(() => { stopPolling(); }); return { onBefore() { stopPolling(); }, onCancel() { stopPolling(); }, onAfter() { if (queryInstance.error.value && errorRetryCountRef.value !== 0) return; if (!pollingWhenHidden && !visible.value) { addUnsubscribeList(subscribe(() => queryInstance.context.refresh())); return; } pollingTimer.value = polling(() => queryInstance.context.refresh()); } }; } ); export { usePollingPlugin as default }; //# sourceMappingURL=usePollingPlugin.js.map