Skip to content

Worker Computed ​

useWorkerComputed() (vue-worker-kit/computed) — a computed() that recalculates inside a worker whenever its reactive source changes, with stale runs discarded automatically.

ts
import { useWorkerComputed } from 'vue-worker-kit/computed'

const sorted = useWorkerComputed<typeof import('./heavy-sort.worker')>(
  () => new Worker(new URL('./heavy-sort.worker.ts', import.meta.url), { type: 'module' }),
  () => list.value, // tracked like a watchEffect source
  { debounce: 150 },
)

// sorted.value — undefined until the first result, then the latest CURRENT result
// sorted.isRunning, sorted.error

Race handling: every run gets an internal generation number. If the source changes again before a run's result arrives, that result is simply dropped on arrival (never rolls sorted.value back to a stale value), and the superseded run's ctx.signal is aborted (cooperative — the handler decides whether to check it, for example with await ctx.yield()). Pass worker: { hardCancelOnAbort: true } to terminate the busy worker instead of letting a stale computation run to the end.

Parameters ​

factory ​

() => Worker

Same worker factory as useWorker().

source ​

() => In

Tracked like a watchEffect source — re-runs the worker whenever any reactive dependency read inside it changes.

options ​

debounce ​

number

Delay in ms before firing the worker on a source change — prevents firing on every reactive tick (e.g. on each keystroke).

worker ​

UseWorkerOptions

Options passed to the internal useWorker(): hardCancelOnAbort, concurrency, retries, idleTimeout, unwrap and so on.

immediate ​

boolean · default: true

Whether the first run starts right away. With false nothing runs until the source changes or refresh() is called.

Return value ​

sorted above is a ShallowRef-like object:

value ​

Out | undefined

undefined until the first result arrives, then always the latest non-stale result.

isRunning ​

ComputedRef<boolean>

error ​

ShallowRef<WorkerError | null>

refresh() ​

() => void

Runs the worker again for the current source at once, skipping debounce — useful for a "Recalculate" button, or as the first trigger with immediate: false.

useWorkerComputed() doesn't have a cache option — its own generation-number mechanism already discards stale/superseded results, and its source() typically produces a fresh input on every reactive tick anyway, so key-based memoization wouldn't have much to hit.