2017-02-03 46 views
8

我有一個運行每次三個不同的行動終極版傳奇「WATCHLIST_FETCH_REQUEST」被分派:如何等待/屈服於單個redux可觀察史詩中的多個動作?

function* watchFetchWatchlist() { 
    yield takeLatest('WATCHLIST_FETCH_REQUEST', fetchWatchlist); 
} 


function* fetchWatchlist() { 
    const activity = 'ACTIVITY_FETCH_WATCHLIST'; 
    yield put(
    addNetworkActivity(activity) // Action 1: enables a global loading indicator before request is made 
); 
    const { response, error } = yield call(
    api.fetchWatchlist // make an API request 
); 
    yield put(
    removeNetworkActivity(activity) // Action 2: removes the above global loading indicator after request completes 
); 
    if (response) { 
    yield put(
     updateUserWatchlist(response) // Action 3a: updates Redux store with data if response was successful 
    ); 
    } else { 
    yield put(
     watchlistFetchFailed(error) // Action 3b: updates Redux store with error if response failed 
    ); 
    } 
} 

這個傳奇的流程在本質上是同步的。操作1必須首先運行以設置應用程序的全局加載狀態。操作2必須在操作1之後運行,並且在網絡活動完成後,API響應返回以移除全局加載狀態後。

我對redux-observable很新,但我一直在挖掘很多嘗試找出如何將這個傳奇轉換成史詩。這裏的兩個目標:

  1. 順序執行的動作,一前一後,相對於在平行
  2. 運行執行以下操作/流程在單個史詩(:「WATCHLIST_FETCH_REQUEST」被燒製時類型序幕)

你如何通過可重複觀察來實現這一點?謝謝!

回答

3

我找到了答案,我的問題通過拼湊談話這裏的若干部分:https://github.com/redux-observable/redux-observable/issues/62

我結束了沿着線的東西:

import { concat as concat$ } from 'rxjs/observable/concat'; 
import { from as from$ } from 'rxjs/observable/from'; 
import { of as of$ } from 'rxjs/observable/of'; 


export const fetchWatchlistEpic = (action$) => { 
    const activity = 'ACTIVITY_FETCH_WATCHLIST'; 

    return action$.ofType('WATCHLIST_FETCH_REQUEST') 
    .switchMap(() => 
     concat$(
     of$(addNetworkActivity(activity)), 
     from$(api.fetchWatchlist()) 
      .map((data) => Immutable.fromJS(data.response)) 
      .switchMap((watchlist) => 
      of$(
       updateUserWatchlist(watchlist), 
       removeNetworkActivity(activity), 
      ) 
     ) 
    ) 
    ); 
}; 

concatof似乎是去 - 嘗試按順序運行多個操作時的操作符。

相關問題