Search code examples
angularrxjsngrx

How to dispatch actions every ten seconds and stop them on another action?


In my application I have actions: 'GET_USER', 'GET_DOCS'.

I want to dispatch those actions every ten seconds using effects.

for example, in some component I dispatch an action: startAutoDispatch, the effects catch this action and start dispach others actions every ten seconds.

Something like this effect:

createEffects(() => this.actions$.pipe(
 ofType('startAutoDispatch')
 switchMap(() => ([
  { type: 'GET_USER', payload: null },
  { type: 'GET_DOCS', payload: null }
 ])

This is not works. and I don't have the timer to dispatch those actions again and again.

Also I want if the action stopAutoDispatch dispatch then stop the timer.

How can I solve this issue in rxjs way/ngrx way?


Solution

  • createEffects(() =>
      this.actions$.pipe(
        ofType('startAutoDispatch'),
        switchMap(() =>
          timer(0, 10 * 1000).pipe(
            mergeMap(() =>
              from([
                { type: 'GET_USER', payload: null },
                { type: 'GET_DOCS', payload: null },
              ])
            ),
            takeUntil(this.actions$.pipe(ofType('stopAutoDispatch')))
          )
        )
      )
    );
    
    • listen for the start
    • use timer to repeatedly emit the 2 actions you want
    • stop dispatching those actions if the stopAutoDispatch is dispatched (until startAutoDispatch is dispatched again)