Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispatch an empty action?

Tags:

I am using ngrx/effects.

How can I dispatch an empty action?

This is how I am doing now:

 @Effect() foo$ = this.actions$     .ofType(Actions.FOO)     .withLatestFrom(this.store, (action, state) => ({ action, state }))     .map(({ action, state }) => {       if (state.foo.isCool) {         return { type: Actions.BAR };       } else {         return { type: 'NOT_EXIST' };       }     }); 

Since I have to return an action, I am using return { type: 'NOT_EXIST' };.

Is there a better way to do this?

like image 517
Hongbo Miao Avatar asked Sep 29 '16 05:09

Hongbo Miao


2 Answers

I've used similar unknown actions, but usually in the context of unit tests for reducers.

If you are uneasy about doing the same in an effect, you could conditionally emit an action using mergeMap, Observable.of() and Observable.empty() instead:

@Effect() foo$ = this.actions$   .ofType(ChatActions.FOO)   .withLatestFrom(this.store, (action, state) => ({ action, state }))   .mergeMap(({ action, state }) => {     if (state.foo.isCool) {       return Observable.of({ type: Actions.BAR });     } else {       return Observable.empty();     }   }); 
like image 183
cartant Avatar answered Sep 16 '22 11:09

cartant


The choosen answer does not work with rxjs6 any more. So here is another approach.

Although I prefer filtering for most cases as described in an another answer, using flatMap can sometimes be handy, especially when you are doing complex stuff, too complicated for a filter function:

import { Injectable } from '@angular/core'; import { Actions, Effect, ofType } from '@ngrx/effects'; import { flatMap } from 'rxjs/operators'; import { EMPTY, of } from 'rxjs';  @Injectable() export class SomeEffects {   @Effect()   someEffect$ = this._actions$.pipe(     ofType(SomeActionTypes.Action),     flatMap((action) => {       if (action.payload.isNotFunny) {         return of(new CryInMySleepAction());       } else {         return EMPTY;       }     }),   );    constructor(     private _actions$: Actions,   ) {   } } 
like image 36
hugo der hungrige Avatar answered Sep 18 '22 11:09

hugo der hungrige