I am building an app that will fetch data from a websocket, and the size of entity will increase overtime. I want to remove the old items when the size exceeds maximum. I currently use selectTotal$ to get the current size of the entity and if it exceeds maximum, then I will call removeMany(ids) to delete the old items. However, I don't think this is a good way, because the selectTotal$ will be triggered again. Should I do this in reducer when upserting items to the entity?
My current implementation:
this.store.selectTotal$
.pipe(
filter((t) => t > MAX_COUNT),
switchMapTo(this.store.ids$)
)
.subscribe((ids) => {
const removals = ids.slice(MAX_COUNT);
this.store.removeMany(removals);
});
You can write an effect, that will listen to the websocket push but it won't save the data directly. Instead it will check for the current state, calculate a new one and then it'll dispatch an action to actually save the data to the store.
Something like this:
someEffect$ = createEffect(() =>
this.acitons$.pipe(
ofType(processDataPushAction),
withLatestFrom(this.store.selectAll), // Get all entities currently in store
map(([<action.payload>, allData]) => {
let calcResult; //
if (allData.length > MAX_COUNT) {
// splice and assign to calcResult
} else {
calcResult = <action.payload>;
}
return saveDataAction({ calcResult });
})
)
)