profiler
profiler

Reputation: 627

Dispatch action periodically in NGRX 8 and Angular

I can't find similar functionality in NGRX documentation. But also I have no big experience in that library.

But - there is a possibility to dispatch action (and effect to send GET request to backend) periodically?

For example, if first dispatch action got empty response - re-dispatch action after 5 minutes.

Upvotes: 1

Views: 1739

Answers (2)

Hadrien TOMA
Hadrien TOMA

Reputation: 2723

When it is needed to have the interval argument in store, you can use:

    ping$ = createEffect(
        () =>
            this.actions$.pipe(ofType(startPinging)).pipe(
                withLatestFrom(this.store.select(pingPeriodAsMs)),
                exhaustMap(([_, pingPeriodAsMs]) => timer(pingPeriodAsMs, pingPeriodAsMs)),
                mapTo(ping())
            ),
        { dispatch: true }
    );

Actions

  • startPinging: the start of the loop is requested
  • ping: an iteration of the loop occured, ping!

Reducers

  • pingPeriodAsMs: number, amount of time between two pings (in the example of code given, this value is also used for the delay of the first ping).

RxJS

Functions

Operators

EDITS

Supposing that at some point we need to stop interval (thanks @AhammadaliPK for the question), the following code should do the trick:


  private stopPinging$ = new Subject<void>();

  ping$ = createEffect(
    () =>
      this.actions$.pipe(ofType(startPinging)).pipe(
        withLatestFrom(this.store.pipe(select(pingPeriodAsMs))),
        exhaustMap(([_, pingPeriodAsMs]) =>
          timer(pingPeriodAsMs).pipe(
            takeUntil(this.stopPinging$)
          )
        ),
        mapTo(ping())
      ),
    { dispatch: true }
  );

  stopPinging() {
    this.stopPinging$.next();
  }

Upvotes: 3

timdeschryver
timdeschryver

Reputation: 15505

NgRx Effects is the right place to do this:

@Effect()
ping = interval(1000).pipe(mapTo(new Ping()));

For more info see: https://timdeschryver.dev/posts/start-using-ngrx-effects-for-this

Upvotes: 4

Related Questions