asyncSignalGroup Function
Creates a new AsyncSignalGroup instance that manages the lifecycle of an asynchronous action, including emitters for launching the action, handling its success, dealing with failures, and maintaining the signal state of the asynchronous action.
The signal state can be used in Angular’s effect
or computed
functions and in other places
where you would normally use a signal.
This function also allows for an optional onInit
callback, which can be used to perform
additional setup or configuration just before the group initialization.
The fallback value is used as a default success value in case the asynchronous action fails, ensuring that the success emitter always returns a value
@template L
The type representing the data for the launch emitter
@template S
The type representing the data for the success emitter
@template F
The type representing the error data for the fail emitter
@param onInit?: (group: AsyncSignalGroup<L, S, F>, sameGroup: AsyncSignalGroup<L, S, F>) => void
An optional callback function executed just before the group initialization
@param fallbackValue?: S
An optional fallback value of type S
that will be used as the default success value if
the asynchronous action fails
@returns AsyncSignalGroup<L, S, F>
API
function asyncSignalGroup<L, S, F>(
onInit?: (group: AsyncSignalGroup<L, S, F>, sameGroup: AsyncSignalGroup<L, S, F>) => void,
fallbackValue?: S,
): AsyncSignalGroup<L, S, F>;
Example
import {computed} from '@angular/core';
import {switchMap} from 'rxjs';
import {transmit} from '@bitfiber/rx';
import {signalState, asyncSignalGroup} from '@bitfiber/ng/rx';
interface Product {
id: number;
name: string;
price: number;
}
interface ProductsState {
products: Product[];
isLoading: boolean;
}
// Provides an async group for managing products loading process
const productsReq = asyncSignalGroup<number, Product[], Error>((group, {
launch, success, fail, finish,
}) => {
group
// Keeps cached data for 120 seconds, with a maximum entry count of 10
.useCache(120, 10);
launch
// Defines a side effect for loading products
.effect(switchMap(page => productsService.get(`api/products?page=${page}`)
.pipe(transmit(group))));
success
// Performs a tap callback each time the request succeeds
.tap(data => console.log(data));
fail
// Performs a tap callback each time the request fails
.tap(error => console.log(error));
finish
// Performs a tap callback each time the request either fails or succeeds
.tap(() => console.log('Request has been finished'));
}, []);
// Provides the main state
const data = signalState<ProductsState>({products: [], isLoading: false}, s => s
// Receives request success data
.receive(productsReq.success, (products, state) => ({...state, products}))
);
// Provides the loading status state
const isLoading = computed(() => productsReq.state().inProgress);
// Starts the products loading process
productsReq.launch.emit(1);