FairPluto
FairPluto

Reputation: 737

Wait for RxJS dispatch to resolve

I'm trying to implement a "next step" feature on my Angular 6 webapp. When the user hit the "next step" button, the front dispatch an action that update the db with the datas in store, an other action that retrieve some processed datas on a Spring API and finally, it changes the step to the "next step".

My problem here is that the inner dispatch are asynchronous, and the request are all processed in a random order, except that it requires to be in the right order, for the datas to be ok.

Here is my dispatchs :

nextStep() {
    this.tseProjectStore.dispatch(
      new fromTSEProjectStore.UpdateProject(this.currentTSEProject, this.pathArchitecture, true, '')
    );
    this.tseProjectStore.dispatch(
      new fromTSEProjectStore.SetSolution(this.currentTSEProject, this.pathInitSolution)
    );
    this.router.navigate(['adjustments-step', this.currentTSEProject.id], {relativeTo: this.route.parent.parent});
  }

Is there any way to "wait" for these dispatch to resolve before continuing runing the code ?

Upvotes: 2

Views: 2042

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26430

Long story short, you can't. The dispatch is not waitable it just sends an action to the store.

What you can do is the following:

  1. Don't use stores and switch to observables which are waitable (with the await keyword).
  2. If you can't switch to observables, a signalling method should be used. When the action is completed a javascript event can be sent.
  3. Looks like you need one state that includes all the data. Create a more extended state and when you send the action, change all the aspects of the state at once.

You can chain dispatch using ngrx effect: https://medium.com/@amcdnl/dispatching-multiple-actions-from-ngrx-effects-c1447ceb6b22

Upvotes: 1

Related Questions