0

我正在尝试debounce()使用Observablepipe()链接.subscribe(),但由于某种原因,订阅中的函数仍然一次被调用了十几次。

我正在尝试做的是管道withChangesForTables和去抖动同步调用,因为我希望仅在进行了整批更改时才调用它。所以我为同步创建了一个提供程序并将它包裹在我的 RootNavigator 周围

withChangesForTables关于西瓜数据库源代码

const SyncContext = createContext();
function useSync() {
    return useContext(SyncContext);
}

function SyncProvider({children}) {
    const [isSyncing, setIsSyncing] = useState(false);
    const [hasUnsynced, setHasUnsynced] = useState(false);

    async function checkUnsyncedChanges() {
        const hasChanges = await hasUnsyncedChanges({
            database
        });
        setHasUnsynced(hasChanges);
    }
    async function sync() {
        await checkUnsyncedChanges();
        if (!isSyncing && hasUnsynced) {
            setIsSyncing(true);
            await synchronizeWithServer();
            setIsSyncing(false);
        }
    }

    
    database.withChangesForTables([
        'table_name',
        'table_name2'
    ]).pipe(
        skip(1),
        // ignore records simply becoming `synced`
        filter(changes => !changes.every(change => change.record.syncStatus === 'synced')),
        // debounce to avoid syncing in the middle of related actions - I put 100000 to test only
        debounceTime(100000),
    ).subscribe({
        //calls API endpoint to sync local DB with server
        next: () => sync(), 
        error: e => console.log(e)
    });

    const value = {
        isSyncing,
        hasUnsynced,
        checkUnsyncedChanges,
        sync
    };

    return (
        <SyncContext.Provider value={value}>
            {children}
        </SyncContext.Provider>
    );
}
4

1 回答 1

0

我必须withChangesForTables进入 auseEffect并重新运行它才能取消订阅,这似乎已经解决了这个问题。代码现在看起来像这样:

useEffect(() => {
    return database.withChangesForTables([
        'table_name',
        'table_name2'
    ]).pipe(
        skip(1),
        filter(changes => !changes.every(change => change.record.syncStatus === 'synced')),
        debounceTime(500),
    ).subscribe({
        next: () => sync(), 
        error: e => console.log(e)
    });
}, [])
于 2022-01-04T21:34:18.457 回答