RxJS 扫描和过滤与 bufferCount 问题

问题描述 投票:0回答:1

我在玩ngrx效果和rxjs时遇到问题。我正在使用两个版本的效果(为了解决这个问题而进行了简化):

版本1:

public effect$ = createEffect(() =>
    this.actions$.pipe(
      ofType(
        actions.successAction1,
        actions.successAction2,
        ...
      ),
      scan((actionCount, typedAction) => actionCount + 1, 0),
      filter((actionCount) => actionCount === 2), // If more actions, then this value is different
      map((actionCount) => actions.finalAction())
    )
  );

版本2:

public effect$ = createEffect(() =>
    this.actions$.pipe(
      ofType(
        actions.successAction1, 
        actions.successAction2
        ...
      ),
      bufferCount(2), // If more actions, then this value is different
      switchMap(() => actions.finalAction())
    )
  );

我真的不明白为什么第一个版本可以工作,而第二个版本却不能。我希望在调度 2 个操作(successAction1 和 successAction2)后调度“finalAction”。

angular typescript rxjs ngrx rxjs-pipeable-operators
1个回答
0
投票

bufferCount(2)
运算符将两个操作收集到一个数组中,但您需要在分派之前将该数组映射到
finalAction

public effect$ = createEffect(() =>
  this.actions$.pipe(
    ofType(
      actions.successAction1,
      actions.successAction2
      // ... add other action types
    ),
    bufferCount(2),
    filter((bufferedActions) => bufferedActions.length === 2),
    switchMap((bufferedActions) => [
      actions.finalAction(),
      // You can also include the buffered actions if needed
      // actions.someOtherAction(bufferedActions[0], bufferedActions[1]),
    ])
  )
);
© www.soinside.com 2019 - 2024. All rights reserved.