Skip to main content

Function: rxMutation()

rxMutation<Parameter, Result>(optionsOrOperation): Mutation<Parameter, Result>

Defined in: libs/ngrx-toolkit/src/lib/mutation/rx-mutation.ts:89

Creates a mutation that leverages RxJS.

For each mutation the following options can be defined:

  • operation: A function that defines the mutation logic. It returns an Observable.
  • onSuccess: A callback that is called when the mutation is successful.
  • onError: A callback that is called when the mutation fails.
  • operator: An optional wrapper of an RxJS flattening operator. By default concat sematics are used.
  • injector: An optional Angular injector to use for dependency injection.

The operation is the only mandatory option.

The returned mutation can be called as an async function and returns a Promise. This promise informs about whether the mutation was successful, failed, or aborted (due to switchMap or exhaustMap semantics).

The mutation also provides several Signals such as error, status or isPending (see below).

Example usage without Store:

const counterSignal = signal(0);

const increment = rxMutation({
operation: (param: Param) => {
return calcSum(this.counterSignal(), param.value);
},
operator: concatOp,
onSuccess: (result) => {
this.counterSignal.set(result);
},
onError: (error) => {
console.error('Error occurred:', error);
},
});

const error = increment.error;
const isPending = increment.isPending;
const status = increment.status;
const value = increment.value;
const hasValue = increment.hasValue;

async function incrementCounter() {
const result = await increment({ value: 1 });
if (result.status === 'success') {
console.log('Success:', result.value);
}
if (result.status === 'error') {
console.log('Error:', result.error);
}
if (result.status === 'aborted') {
console.log('Operation aborted');
}
}

function calcSum(a: number, b: number): Observable<number> {
return of(result).pipe(delay(500));
}

Type Parameters

Parameter

Result

Parameters

optionsOrOperation

RxMutationOptions<Parameter, Result> | Operation<Parameter, Observable<Result>>

Returns

Mutation<Parameter, Result>

the actual mutation function along tracking data as properties/methods