( source: () => T, wait: NoInfer<DebounceTimer<T>>, options?: NoInfer<DebouncedOptions<T>>, )
| 33 | * @see [Debouncing signals with `debounced`](guide/signals/debounced) |
| 34 | */ |
| 35 | export function debounced<T>( |
| 36 | source: () => T, |
| 37 | wait: NoInfer<DebounceTimer<T>>, |
| 38 | options?: NoInfer<DebouncedOptions<T>>, |
| 39 | ): Resource<T> { |
| 40 | if (isInParamsFunction()) { |
| 41 | throw invalidResourceCreationInParams(); |
| 42 | } |
| 43 | if (ngDevMode && !options?.injector) { |
| 44 | assertInInjectionContext(debounced); |
| 45 | } |
| 46 | const injector = options?.injector ?? inject(Injector); |
| 47 | |
| 48 | let active: Promise<void> | void | undefined; |
| 49 | let pendingValue: T | undefined; |
| 50 | let activeTimer: ReturnType<typeof setTimeout> | undefined; |
| 51 | |
| 52 | const cancelTimer = () => { |
| 53 | if (activeTimer !== undefined) { |
| 54 | clearTimeout(activeTimer); |
| 55 | activeTimer = undefined; |
| 56 | } |
| 57 | }; |
| 58 | |
| 59 | injector.get(DestroyRef).onDestroy(() => { |
| 60 | cancelTimer(); |
| 61 | active = undefined; |
| 62 | }); |
| 63 | |
| 64 | const state = linkedSignal< |
| 65 | {value: T; thrown: false} | {error: unknown; thrown: true}, |
| 66 | ResourceSnapshot<T> |
| 67 | >({ |
| 68 | source: () => { |
| 69 | try { |
| 70 | setInParamsFunction(true); |
| 71 | return {value: source(), thrown: false}; |
| 72 | } catch (err) { |
| 73 | rethrowFatalErrors(err); |
| 74 | return {error: err, thrown: true}; |
| 75 | } finally { |
| 76 | setInParamsFunction(false); |
| 77 | } |
| 78 | }, |
| 79 | computation: (res, previous) => { |
| 80 | // If we already have a state from the effect or a previous read, keep it! |
| 81 | // The effect is responsible for timing and state transitions. |
| 82 | if (previous !== undefined) { |
| 83 | return previous.value; |
| 84 | } |
| 85 | |
| 86 | // On the very first evaluation, determine the initial state synchronously. |
| 87 | if (res.thrown) { |
| 88 | return {status: 'error', error: res.error as Error}; |
| 89 | } |
| 90 | return {status: 'resolved', value: res.value}; |
| 91 | }, |
| 92 | }); |
no test coverage detected