簡體   English   中英

如何在 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 })
    )
  );

設置警報,然后在設定的時間段后關閉相同的警報 [...] 在警報自動關閉之前,用戶可以手動關閉警報

考慮到這一點,這是我的方法:

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可以是作為用戶操作的結果發送next通知的Subject 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM