My question is: Can a service listen to state change and make an http call based on the state value, or does it have to be triggered by an effect(NgRx) ? So instead of having a service called by an effect like in the examples you usually find on the web, you'd have a service listening to a part of the store and react based on that. And thus no more effect. My question is more of a philosophical (best practices) question than a technical question because, technically, both work.
Update
Here is a concrete case to understand why I'm asking:
Context :
I have a list of elements that I receive from my backend. I can filter that list of elements. There can be more than one filter at a time. The filtering is done on the backend side.
Current implementation:
The component dispatches a FILTER_ELEMENTS action. That action is picked up by an effect that calls the http service. the service asks the backend for a list of elements based on the filter(s).
Because there can be more than one filter, the effect (or the service) needs to know what are the current filters and add the new one to that list. So I added a .withLatestFrom(this.state$) in the effect and a get the current list of filters from there.
Problem:
The problem is that the state is not updated with the new filter. I could catch the FILTER_ELEMENTS action with in my reducer and update the state but that would cause several other potential problems.
Which of the effect and the reducer will be called first?
What if there is a backend error? my state is updated with the new filter but the list is not filtered.
What about asynchornism ? what if I ask for another filter before the sever answers or before the state is updated?
This seems a little bit too messy to me.
So my question is:
What about the store really is the signle source of truth ? Instead not just a "log" of what happened that is maybe or maybe not up to date. I mean that a componenent that want to add a filter can do so by dispatching a ADD_FILTER action that would update the list of filter in the state. And my service could listen to the list of filters and call the backend everytime the list changes.
So the service only calls the backend when the state changes and with what we know is the latest and real state. And then dispatch a "success" action to the store with the updated list.
I don't see how that would cause more potential infinite loops than the effects... After all, the effects can also cause infinite loops...
So my service would in fact be an effect that listens to store changes instead of directly to actions.