| 1 | import { computed, shallowRef, watch } from 'reactive-vscode' |
| 2 | |
| 3 | export function useDebouncedComputed<T>(source: () => T, delay: (newVal: T, oldVal: T) => number | null) { |
| 4 | const result = shallowRef(source()) |
| 5 | let timeout: NodeJS.Timeout | undefined |
| 6 | watch( |
| 7 | source, |
| 8 | (newVal, oldVal) => { |
| 9 | clearTimeout(timeout) |
| 10 | const d = delay(newVal, oldVal) |
| 11 | if (d == null) { |
| 12 | result.value = newVal |
| 13 | } |
| 14 | else { |
| 15 | timeout = setTimeout(() => { |
| 16 | result.value = newVal |
| 17 | }, d) |
| 18 | } |
| 19 | }, |
| 20 | ) |
| 21 | return computed<T>(() => result.value) |
| 22 | } |
| 23 |