我如何在 redux-observable 史诗中链接 RxJS observable?

How can I chain RxJS observable in a redux-observable epic?

我刚开始学习 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 })
    )
  );

感谢您的帮助!

为 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 })
    )
  );

set an alert, then after a set period, close that same alert [...] he user could manually close one alert before it automatically closes itself

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

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 })
}