d0x
d0x

Reputation: 11601

How to cancel ngxs dispatch actions

How to cancel a running store.dispatch(xxx) action, so that the underlying http requests are canceled as well?

I tried to .unsubscribe() from a store.dispatch(new FetchSomeStuffOverHttp()) call and expected that the underlying http request is also canceled.

But it will continue to run, even if the httpClient's observable is returned by the action:

@Action(FetchStuffOverHttp)
fetchStuffOverHttp({ patchState }: StateContext<AuftragStateModel>) {
  return this.httpClient.get(...)
                        .pipe(
                            tap((...) => {  patchState(...) })
                         )
}

Is it the expected behaviour that store.dispatch(xxx).subscribe().unsubscribe() is not unsubscribing/canceling the httpClients observable?

In contrast, the { cancelUncompleted: true } option will cancel the underling http request.

Upvotes: 3

Views: 1920

Answers (1)

kctang
kctang

Reputation: 11202

Q: How to cancel a running store.dispatch(xxx) action, so that the underlying http requests are canceled as well?

A: If the underlying http request is within an observable chain returned by the action (i.e. an async action), then dispatching same action with { cancelUncompleted: true } will cancel the previously dispatch action if it is still running.

If you want to cancel a running async action without dispatching to it again, you will have to deal it from the action's observable yourself (e.g. using appropriate rxjs patterns like the takeUntil() operator).

Q: Is it the expected behaviour that store.dispatch(xxx).subscribe().unsubscribe() is not unsubscribing/canceling the httpClients observable?

A: Yes. AFAIK, this is by design & expected behavior.

Upvotes: 3

Related Questions