1

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);
  });
Chi
  • 355
  • 4
  • 14
  • I would try to use an `effect` for this to keep the reducer pure. And that way you don't need to listen to the total count but handle it while saving data to the store – mat.hudak Oct 13 '21 at 09:49
  • @dallows Yes, I have an `effect` to upsert items to entity, but the websocket won't send all items when some items are added or updated, it only sent all at first time I subscribe to it, so I still need to listen to `selectTotal$` or `entities$` with `withLatestFrom` to get the current size of entity and remove old items in that effect. – Chi Oct 13 '21 at 10:31

1 Answers1

0

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 });
    })
  )
)
mat.hudak
  • 2,803
  • 2
  • 24
  • 39