@augmentcode/ag-redux-toolkit
Version:
Redux + Saga state management for Svelte apps — designed for AI agents. Includes runtime TypeScript source, AI skills, and reference documentation for robust, observable, high-performance state management.
54 lines (53 loc) • 2.3 kB
JavaScript
import { cancel, delay, fork, put, take } from "typed-redux-saga";
//#region src/utils/sagas/debounce-saga.ts
/**
* Creates a legacy wrapper-action debouncing saga that can handle multiple
* different actions.
*
* This saga takes an action that wraps another action as its payload,
* and debounces the inner action. It maintains separate debounce timers
* for each unique action type, so different actions can be debounced
* independently.
*
* @deprecated Wrapper-action debounce is retained for compatibility only. For
* new debounce logic, watch the real action directly with `takeLatest` or
* `takeLeading`, then `delay` inside the worker before running the effect.
*
* @param wrapperActionCreator - The action creator that wraps other actions
* @param debounceMs - Debounce delay in milliseconds
*/
function* debounceSaga(wrapperActionCreator, debounceMs) {
yield* debounceWithKeySaga(wrapperActionCreator, debounceMs, (action) => action.type);
}
/**
* Creates a legacy wrapper-action debouncing saga with a custom key extractor.
*
* This allows you to debounce based on custom logic, not just action type.
* For example, you might want to debounce per user ID, per conversation ID, etc.
*
* @deprecated Wrapper-action debounce is retained for compatibility only. For
* new debounce logic, watch the real action directly with `takeLatest` or
* `takeLeading`, then `delay` inside the worker before running the effect.
*
* @param wrapperActionCreator - The action creator that wraps other actions
* @param debounceMs - Debounce delay in milliseconds
* @param keyExtractor - Function to extract a unique key from the inner action
*/
function* debounceWithKeySaga(wrapperActionCreator, debounceMs, keyExtractor) {
const debounceTasks = /* @__PURE__ */ new Map();
while (true) {
const [innerAction] = (yield* take(wrapperActionCreator)).payload;
const debounceKey = keyExtractor(innerAction);
const existingTask = debounceTasks.get(debounceKey);
if (existingTask) yield* cancel(existingTask);
const newTask = yield* fork(function* () {
yield* delay(debounceMs);
yield* put(innerAction);
debounceTasks.delete(debounceKey);
});
debounceTasks.set(debounceKey, newTask);
}
}
//#endregion
export { debounceSaga, debounceWithKeySaga };
//# sourceMappingURL=debounce-saga.js.map