()
| 24 | * @returns A new notify manager. |
| 25 | */ |
| 26 | export function createNotifyManager() { |
| 27 | let queue: Array<NotifyCallback> = [] |
| 28 | let transactions = 0 |
| 29 | let notifyFn: NotifyFunction = (callback) => { |
| 30 | callback() |
| 31 | } |
| 32 | let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => { |
| 33 | callback() |
| 34 | } |
| 35 | let scheduleFn = defaultScheduler |
| 36 | |
| 37 | const schedule = (callback: NotifyCallback): void => { |
| 38 | if (transactions) { |
| 39 | queue.push(callback) |
| 40 | } else { |
| 41 | scheduleFn(() => { |
| 42 | notifyFn(callback) |
| 43 | }) |
| 44 | } |
| 45 | } |
| 46 | const flush = (): void => { |
| 47 | const originalQueue = queue |
| 48 | queue = [] |
| 49 | if (originalQueue.length) { |
| 50 | scheduleFn(() => { |
| 51 | batchNotifyFn(() => { |
| 52 | originalQueue.forEach((callback) => { |
| 53 | notifyFn(callback) |
| 54 | }) |
| 55 | }) |
| 56 | }) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | return { |
| 61 | /** |
| 62 | * Batches all updates scheduled inside the passed callback. |
| 63 | * This is mainly used internally to optimize query client updating. |
| 64 | * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes. |
| 65 | * The return value of `callback` is passed through. |
| 66 | * @param callback - The function to run in the batch. |
| 67 | * @returns The return value of `callback`. |
| 68 | */ |
| 69 | batch: <T>(callback: () => T): T => { |
| 70 | let result |
| 71 | transactions++ |
| 72 | try { |
| 73 | result = callback() |
| 74 | } finally { |
| 75 | transactions-- |
| 76 | if (!transactions) { |
| 77 | flush() |
| 78 | } |
| 79 | } |
| 80 | return result |
| 81 | }, |
| 82 | /** |
| 83 | * All calls to the wrapped function will be batched. |
no test coverage detected