【问题标题】:Interval API calls in Redux-ObservableRedux-Observable 中的间隔 API 调用
【发布时间】:2018-03-31 13:50:47
【问题描述】:

我已经开始在 React 中使用 redux-observable 并且我坚持使用间隔 API 请求。

这是我的史诗的代码,效果很好,但仅适用于单个请求:

const fetchPointValue = (action$) =>
  action$
    .ofType(actionTypes.REQUEST_POINT_VALUE)
    .mergeMap(action =>
          ajax.getJSON(`${API_SERVER_URL}/point/value/${action.payload.id}`)
            .map(response => receivePointValue(action.payload.id, response))
            .startWith(fetchingPointValue(action.payload.id))
    )

现在,我需要将其修改为间隔 - 如果调用了操作 REQUEST_POINT_VALUE,我需要每隔约 5 秒请求一次值,直到 REQUEST_POINT_CANCEL 操作。 可能使用 .takeUntil("REQUEST_POINT_CANCEL").interval(5000) 可以解决我的问题,但我尝试了所有可能的组合,但仍然无法达到工作版本。

【问题讨论】:

    标签: reactjs rxjs react-redux redux-observable


    【解决方案1】:

    是的,您可以使用.interval.takeUntill 实现此目的:

    action$
      .ofType(actionTypes.REQUEST_POINT_VALUE)
      .mergeMap(action =>
        Observable
          .interval(5000)
          .switchMap(/* make request here */)
          .takeUntil(action$.ofType(actionTypes.REQUEST_POINT_CANCEL))
      )
    

    在此处查看文档和示例 - 3.1 Cancellation

    【讨论】:

    • 很好的答案!另外:如果您希望第一个请求立即开始,而不是等待前 5000 毫秒,您可以使用 Observable.interval(5000).startWith(0)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2018-03-19
    • 2019-09-14
    • 2021-01-24
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多