Skip to content

createTask()

The createTask() function is the primary entry point for defining controlled asynchronous actions in ngx-task.

function createTask<TArgs, TResult>(
handler: TaskHandler<TArgs, TResult>,
options?: CreateTaskOptions<TArgs, TResult>,
): Task<TArgs, TResult>;

Handler Function

The handler function receives arguments passed to .run(args) and a TaskContext object:

type TaskHandler<TArgs, TResult> = (
args: TArgs,
context: TaskContext,
) => Promise<TResult> | Observable<TResult>;

Options (CreateTaskOptions)

OptionTypeDefaultDescription
concurrencyConcurrencyPolicy'drop'Concurrency strategy: 'drop', 'restart', 'enqueue', 'latest', or { mode: 'parallel', limit?: number }.
timeoutnumber | TaskTimeoutOptionsundefinedExecution timeout in milliseconds (or object configuration).
pendingDelaynumber0Delay in ms before pending signal becomes true. Prevents micro-flashes for fast operations.
minimumPendingDurationnumber0Minimum time in ms pending signal remains true once activated.
classifyError(err: unknown) => TaskErrorDefault classifierCustom function to wrap and standardize thrown errors into TaskError.
destroyBehavior'cancel' | 'detach' | 'allow''cancel'Behavior when component containing task is destroyed.
injectorInjectorCurrent contextCustom Angular Injector for tasks instantiated outside injection context.
maxQueueSizenumberInfinityMaximum queue size for queued policies (enqueue, parallel).
overflowPolicyQueueOverflowPolicy'reject-newest'Overflow handling when queue is full ('reject-newest', 'drop-oldest', 'throw').
observableResultObservableResultPolicy'latest'Result resolution strategy for Observable handlers ('latest', 'first', 'last', 'forbid-multiple').

Example Usage

const userTask = createTask(
async (userId: string, { signal, reportProgress }) => {
reportProgress({ loaded: 0, total: 100, percentage: 0 });
const user = await fetchUser(userId, { signal });
reportProgress({ loaded: 100, total: 100, percentage: 100 });
return user;
},
{
concurrency: 'restart',
timeout: 5000,
pendingDelay: 200,
minimumPendingDuration: 500,
},
);