2017-02-03 39 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似乎是去 - 尝试按顺序运行多个操作时的操作符。

相关问题