Debounce checks, less noisy

This commit is contained in:
Lim Chee Aun 2023-10-22 19:26:41 +08:00
parent 2149c4c35a
commit 9c4252315a
2 changed files with 59 additions and 45 deletions

View file

@ -1,5 +1,6 @@
import { memo } from 'preact/compat';
import { useEffect, useRef, useState } from 'preact/hooks';
import { useDebouncedCallback } from 'use-debounce';
import { api } from '../utils/api';
import states, { saveStatus } from '../utils/states';
@ -11,9 +12,8 @@ export default memo(function BackgroundService({ isLoggedIn }) {
// - WebSocket to receive notifications when page is visible
const [visible, setVisible] = useState(true);
usePageVisibility(setVisible);
useEffect(() => {
let sub;
if (isLoggedIn && visible) {
const subRef = useRef();
const debouncedStartNotifications = useDebouncedCallback(() => {
const { masto, streaming, instance } = api();
(async () => {
// 1. Get the latest notification
@ -41,7 +41,7 @@ export default memo(function BackgroundService({ isLoggedIn }) {
// 2. Start streaming
if (streaming) {
sub = streaming.user.notification.subscribe();
let sub = (subRef.current = streaming.user.notification.subscribe());
console.log('🎏 Streaming notification', sub);
for await (const entry of sub) {
if (!sub) break;
@ -56,10 +56,18 @@ export default memo(function BackgroundService({ isLoggedIn }) {
}
}
})();
}, 3000);
useEffect(() => {
// let sub;
if (isLoggedIn && visible) {
debouncedStartNotifications();
}
return () => {
sub?.unsubscribe?.();
sub = null;
// sub?.unsubscribe?.();
// sub = null;
debouncedStartNotifications?.cancel?.();
subRef.current?.unsubscribe?.();
subRef.current = null;
};
}, [visible, isLoggedIn]);

View file

@ -238,6 +238,10 @@ function Timeline({
},
[id, loadItems, checkForUpdates, snapStates.settings.autoRefresh],
);
const debouncedLoadOrCheckUpdates = useDebouncedCallback(
loadOrCheckUpdates,
3000,
);
const lastHiddenTime = useRef();
usePageVisibility(
@ -245,12 +249,14 @@ function Timeline({
if (visible) {
const timeDiff = Date.now() - lastHiddenTime.current;
if (!lastHiddenTime.current || timeDiff > 1000 * 60) {
loadOrCheckUpdates({
// 1 minute
debouncedLoadOrCheckUpdates({
disableIdleCheck: true,
});
}
} else {
lastHiddenTime.current = Date.now();
debouncedLoadOrCheckUpdates.cancel();
}
setVisible(visible);
},