hgoebl
hgoebl

Reputation: 13007

Who should subscribe to NGXS async action - the dispatch action caller or the @Action handler?

I don't know whether this is only a matter of style. There are at least 2 ways of handling async actions:

subscribe after dispatch

// action is being dispatched and subscribed
this.store.dispatch(new LoadCustomer(customerId)).subscribe(); // <-- subscribe

In the State:

@Action(LoadCustomer)
loadCustomer(context: StateContext<CustomerStateModel>,
             customerId: string) {
  return this.customerService.loadById(customerId).pipe(
    tap(c => context.setState(produce(context.getState(), draft => {
      draft.byId[customerId] = c;
    })))
  ); // <-- NO subscribe here, just return the Observable
}

subscribe in @Action handler

// action is being dispatched
this.store.dispatch(new LoadCustomer(customerId)); // <-- no subscribe

In the State:

@Action(LoadCustomer)
loadCustomer(context: StateContext<CustomerStateModel>,
             customerId: string) {
  this.customerService.loadById(customerId).pipe(
    tap(c => context.setState(produce(context.getState(), draft => {
      draft.byId[customerId] = c;
    })))
  ).subscribe(); // <-- subscribe is done in action handler
}

Question

Which one is better and why?

Edit / Hint

It turned out that the core issue leading to this question was following: We had an HttpInterceptor caching "too much" which looked liked if some actions had not been executed. In fact the subscription is already handled correctly by NGXS, but in our case no effect was visible (no request in the network tab).

In our cases the .subscribe() calls could be eliminated. Only where we need to wait for an action to finish, a subscription after the dispatch makes sense.

Upvotes: 0

Views: 1110

Answers (2)

Garth Mason
Garth Mason

Reputation: 8001

I think it is somewhat a matter of style, but I'd say (from my usage of NGXS) this is most typical:

On dispatch do this, and only subscribe here if there's some post-action you want to do.

this.store.dispatch(new LoadCustomer(customerId));

And in the state, the option 1 approach, to return the Observable to the NGXS framework and let it handle the subscription itself (see from the docs re: action handling).

Upvotes: 1

foxcodes
foxcodes

Reputation: 31

Approach number one, as there will be only one subscription and the source component/service will be able to react to it. Subscribing in @Action means that whenever the @Action handled is called then new subscription will be created.

Upvotes: 0

Related Questions