dispatch multiple actions in one effect

Lev picture Lev · Jan 17, 2017 · Viewed 35.8k times · Source

I would like to diapatch two actions in one effect. Currently I have to declare two effects to achieve this :

  // first effect
  @Effect() action1$ = this.actions$
    .ofType(CoreActionTypes.MY_ACTION)
    .map(res => {
      return { type: "ACTION_ONE"}
    })
    .catch(() => Observable.of({
      type: CoreActionTypes.MY_ACTION_FAILED
    }));

  // second effect
  @Effect() action2$ = this.actions$
    .ofType(CoreActionTypes.MY_ACTION)
    .map(res => {
      return { type: "ACTION_TWO"}
    })
    .catch(() => Observable.of({
      type: CoreActionTypes.MY_ACTION_FAILED
    }));

Is it possible to have one action, be the source of two actions via a single effect ?

Answer

Javier González picture Javier González · Apr 26, 2017
@Effect()
loadInitConfig$ = this.actions$
    .ofType(layout.ActionTypes.LOAD_INIT_CONFIGURATION)
    .map<Action, void>(toPayload)
    .switchMap(() =>
        this.settingsService
            .loadInitConfiguration()
            .mergeMap((data: any) => [
                new layout.LoadInitConfigurationCompleteAction(data.settings),
                new meetup.LoadInitGeolocationCompleteAction(data.geolocation)
            ])
            .catch(error =>
                Observable.of(
                    new layout.LoadInitConfigurationFailAction({
                        error
                    })
                )
            )
    );