DEV Community

Discussion on: Simple yet powerful state management in Angular with RxJS

Collapse
brotherm profile image
MichaelC • Edited on

Nice, simple approach, Florian. I'm trying it out in my current project.

One question, though: I would like to use a Boolean state object to trigger an action in another component when the value is true. Unfortunately, it only works the first time because of the distinctUntilChanged() operator in select() (I think).

The workaround is to set it to false once it is used in the subscription like so:

    this.appState.reloadProducts$
      .pipe(
        filter(val => val != null && val === true)
      )
      .subscribe(value => {
        this.loadProducts();
        // Reset state
        this.appState.setReloadProducts(false);
      });
Enter fullscreen mode Exit fullscreen mode
reloadProducts$: Observable<boolean> = this.select((state) => state.reloadProducts);
Enter fullscreen mode Exit fullscreen mode

Do you have another suggestion?

Collapse
spierala profile image
Florian Spier Author

I think the reload thing is not really a state, therefore I would not make it part of the state interface. It is more like an action. You can easily create an Action with an RxJS Subject and subscribe on it to trigger the API Call.
You can add that Subject to the service which extends the StateService.

Collapse
brotherm profile image
MichaelC

Excellent suggestion! Thank you.