|
| 1 | +import { ref, watchEffect, Ref } from 'vue'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Handle overlapping async evaluations |
| 5 | + * |
| 6 | + * @param cancelCallback The provided callback is invoked when a re-evaluation of the computed value is triggered before the previous one finished |
| 7 | + */ |
| 8 | +export type AsyncComputedOnCancel = (cancelCallback: () => void) => void; |
| 9 | + |
| 10 | +/** |
| 11 | + * A two-item tuple with the first item being a ref to the computed value and the second item holding a boolean ref, indicating whether the async computed value is currently (re-)evaluated |
| 12 | + */ |
| 13 | +export type AsyncComputedResult<T> = [Ref<T>, Ref<boolean>]; |
| 14 | + |
| 15 | +/** |
| 16 | + * Create an asynchronous computed dependency |
| 17 | + * |
| 18 | + * @param evaluationCallback The promise-returning callback which generates the computed value |
| 19 | + * @param defaultValue A default value, used until the first evaluation finishes |
| 20 | + */ |
| 21 | +export function asyncComputed<T>( |
| 22 | + evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>, |
| 23 | + defaultValue?: T |
| 24 | +): AsyncComputedResult<T> { |
| 25 | + let counter = 0; |
| 26 | + const current = ref(defaultValue) as Ref<T>; |
| 27 | + const evaluating = ref<boolean>(false); |
| 28 | + |
| 29 | + watchEffect(async (onInvalidate: Fn) => { |
| 30 | + counter++; |
| 31 | + const counterAtBeginning = counter; |
| 32 | + let hasFinished = false; |
| 33 | + |
| 34 | + try { |
| 35 | + // Defer initial setting of `evaluating` ref |
| 36 | + // to avoid having it as a dependency |
| 37 | + Promise.resolve().then(() => { |
| 38 | + evaluating.value = true; |
| 39 | + }); |
| 40 | + |
| 41 | + const result = await evaluationCallback((cancelCallback) => { |
| 42 | + onInvalidate(() => { |
| 43 | + evaluating.value = false; |
| 44 | + if (!hasFinished) cancelCallback(); |
| 45 | + }); |
| 46 | + }); |
| 47 | + |
| 48 | + if (counterAtBeginning === counter) current.value = result; |
| 49 | + } finally { |
| 50 | + evaluating.value = false; |
| 51 | + hasFinished = true; |
| 52 | + } |
| 53 | + }); |
| 54 | + |
| 55 | + return [current, evaluating]; |
| 56 | +} |
0 commit comments