[NGXS] Async Action "Fire and Forgot" && "Fire and Wait"

Fire and Forgot: Fire an action and not wait it complete.

Fire and Wait: FIre an action and wait for result.

Fire and Forgot

export class BooksState {
  constructor(private booksService: BooksService) {}

  @Action(GetNovels)
  getNovels(ctx: StateContext<BooksStateModel>) {
    return this.booksService.getNovels().pipe(
      tap(novels => {
        ctx.patchState({ novels }); 
        ctx.dispatch(new GetDetectives()); // Fire GetDetective action not waiting getNovels to complete. Why? because in .subscribe() function for getNoveds() is the actual complete event. now we doing in .tap(), so it is not completed yet
      })
    );
  }

  @Action(GetDetectives)
  getDetectives(ctx: StateContext<BooksStateModel>) {
    return this.booksService.getDetectives().pipe(
      tap(detectives => {
        ctx.patchState({ detectives });
      })
    );
  }
}

Fire and Wait:

Using `mergeMap` or `concatMap, switchMap`

@Action(GetNovels)
getNovels(ctx: StateContext<BooksStateModel>) {
  return this.booksService.getNovels().pipe(
    tap(novels => {
      ctx.patchState({ novels });
    }),
    mergeMap(() => ctx.dispatch(new GetDetectives()))
  );
}

More: https://www.ngxs.io/advanced/actions-life-cycle

原文地址:https://www.cnblogs.com/Answer1215/p/12206200.html