Search code examples
ngxsswitchmap

dispatch ngxs action in switchMap ignoring the return value


There must be a standard way to solve this, but I haven't found anything yet. I am probably not phrasing my search correctly.

I have a search input field and as is good practice, I use the switchmap operator to cancel previous http requests, when the user keeps typing.

I have based this off the example in the ngxs documentation:

this.actions$
  .pipe(
    ofActionDispatched(SomeAction),
    debounceTime(2000),
    distinctUntilChanged(),
    untilDestroyed(this),
    switchMap(() => {
      return this.store.dispatch(new SomeOtherAction());
    })
  ).subscribe(() => {
});

SomeAction is dispatched every time the user types something in the input field and saves in in the store (that's why SomeOtherAction has not constructor parameter).

Is there a better way to do this without having this empty subscribe block? This looks like an anti-pattern.


Solution

  • Another way you could consider is to only dispatch the action to change the searchText in the state after you debounce etc.

    Using the valueChanges Observable on the search input form control you could pipe through a debounce/distinct/filter or whatever combination suits your purposes before calling store.dispatch with your action to modifiy the state.

    Then you'd only modify the state the minimum required times rather than each key press and could also call the HTTP request from there (and I don't think you'd need the action stream subscription in the component).

    Doco for Angular Form valueChanges here