2017-10-19 70 views
1

我已經開始使用React中的redux-observable,並且因間隔API請求而停滯不前。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)可以解決我的問題,但我嘗試了所有可能的組合,仍然無法達到工作版本。

回答

2

是的,你可以使用.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

+2

偉大的答案!另外:如果你想第一個請求立即開始,而不是等待第一個5000毫秒,你可以使用'Observable.interval(5000).startWith(0)' – jayphelps

+0

謝謝你們,它運作良好! – ELP24