【问题标题】:How can I chain RxJS observable in a redux-observable epic?如何在 redux-observable 史诗中链接 RxJS 可观察?
【发布时间】:2021-01-11 08:49:00
【问题描述】:

我最近刚开始学习 redux-observables 和 RxJS 以供工作。我们在 Redux 中设置了全局警报。我希望能够设置警报,然后在设定的时间段后关闭相同的警报。任何时候也可以有多个警报,用户可以在一个警报自动关闭之前手动关闭它。我在这里添加了 id,所以我可以关闭正确的警报。 到目前为止,我试图在初始地图之后使用延迟而不是另一张地图来实现这一点。但是,这会跳过第一张地图。

export const addAlertEpic: Epic<Action, Action, RootState> = (
  action$,
  state$
) =>
  action$.pipe(
    ofType(slice.actions.addAlert),
    map((values: any) =>
      slice.actions.addAlertSuccess({ id: uuid(), ...values.payload })
    )
  );

感谢您的帮助!

【问题讨论】:

    标签: javascript redux rxjs redux-observable


    【解决方案1】:

    设置警报,然后在设定的时间段后关闭同一警报 [...] 用户可以在警报自动关闭之前手动关闭它

    考虑到这一点,这是我的方法:

    actions$.pipe(
      ofType(slice.actions.addAlert),
    
      // `There can also be multiple alerts at any time`
      mergeMap(action => {
        const id = uuid();
    
        // using `NEVER` is important, it's essentially the same as new Observable(() => {})
        // it is needed because we don't want the inner observable to complete unless `takeUntil` decides to
        return NEVER
          .pipe(
    
            // start with opening the alert
            startWith(slice.actions.addAlertSuccess({ id, ...action.payload }))
            
            // close the alert either
            takeUntil(merge(
              
              // when `TIME` expires
              timer(TIME),
              
              // or when the user decides to
              userClosedActions.pipe(
                filter(action => action.id === id)
              )
            )),
    
            // at the end(when the stream completed due to `takeUntil`), close the alert
            endWith(slice.actions.closeAlertSuccess(...))
          )
      })
    )
    

    userClosedActions 可以是一个Subject,作为用户操作的结果发送next 通知。例如:

    onClick (closedId) {
     userClosedActions.next({ id: closedId })
    }
    

    【讨论】:

    • 感谢安德烈的详细回答。我如何创建一个主题并将其与我的史诗联系起来?或者你能指出我正确的方向吗?
    • @ChyMeng 我不确定在这种情况下最好的方法是什么(在 Angular 中它将是依赖注入),但我会在史诗所在的同一个文件中创建主题,然后你可以在你的组件中导入它
    【解决方案2】:

    为 addAlertSucess 添加另一个史诗,包括延迟以调度删除操作。

    export const addAlertSuccessEpic: Epic<Action, Action, RootState> = (
      action$,
      state$
    ) =>
      action$.pipe(
        ofType(slice.actions.addAlertSuccess),
        delay(myTimeToWait),
        map(foo =>
          slice.actions.removeAlert({ id: foo.id })
        )
      );
    

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 2020-12-30
      • 1970-01-01
      • 2018-09-15
      • 2021-08-29
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 2019-02-24
      相关资源
      最近更新 更多