在史诗中,发出一个动作,该动作在完成时发出更多动作

Within an epic, emit an action that emits more actions when it completes

我希望 Action1(下方)的史诗作为可观察对象发出,Action3 然后在完成时发出 Action4 和 Action5。

const action1Epic$ = (action$: Observable<IAction1>, state$: Observable<IState>) => 
    action$.pipe(
        withLatestFromState(state$),
        switchMap(([_action, { stateProp }]) => {
            const somethingUninteresting$ = of(action2(stateProp));
            
            const compoundActions$ = of(action3(stateProp)).pipe(
                mergeMap(act =>
                    merge(...[of(action4(act.stateProp)), of(action5(act.stateProp))])
                )
            );
            return merge(somethingUninteresting$, compoundActions$);
        })
    );

Action3 有史诗:

const action3Epic$ = (action$: Observable<IAction3>, state$: Observable<IState>) => {
    console.log("Action 3 is really happening!")
    return action$.pipe(
       withLatestFromState(state$),
       switchMap(([_action, { stateProp }]) => {
          console.log("API call is happening!");
          return api.doSomething().pipe(
             map(statePropFromResponse => action3Success(statePropFromResponse)
          );
       })
    );
}

结果是我看到了“Action 3 is really happening!”的日志。但从来没有“API 呼叫正在发生!”。在调度程序中,我看到已处理 Action1、Action2、Action4 和 Action5,但从未处理过 Action3。

您需要在合并参数中包含 act 本身。

const compoundActions$ = of(action3(stateProp)).pipe(
  mergeMap(act =>
    merge(...[of(act), of(action4(act.stateProp)), of(action5(act.stateProp))])
  )
);

action1 史诗中的 action3 实例 - mergeMap 回调中的 act - 永远不会作为 Redux 动作发出,因为它不是由史诗中返回的可观察对象发出(特别是 compoundActions$).

您确实订阅了一个发出该动作的可观察对象(of(action3(stateProp) 位),但您仅使用它来创建其他 2 个动作, 这是 compoundActions$.

唯一发出的

p.s.

无关但希望有所帮助:您可以简化创建可观察对象的方式。

merge(...[of(action4(act.stateProp)), of(action5(act.stateProp))]

可以简化为

from([action4(act.stateProp), action5(act.stateProp)])

就此而言 - 我不确定您是否只是在简化 SO 示例的现有代码 - 如果您需要做的只是按顺序发出操作 3、4 和 5,您可以只是做:

const compoundActions$ = from([
  action3(stateProp),
  action4(stateProp),
  action5(stateProp),
]);