redux-observable - dispatch multiple redux actions in a single epic

前端 未结 2 1516
花落未央
花落未央 2020-12-28 12:28

I\'m looking for way of dispatching multiple redux actions in a single Epic of redux-observable middleware.

Let\'s assume I have following Epic. Everyt

相关标签:
2条回答
  • 2020-12-28 13:02

    There is no requirement that you make a one-to-one in/out ratio. So you can emit multiple actions using mergeMap (aka flatMap) if you need to:

    const loaded = (results) => ({type: 'RESULTS_LOADED', results});
    const otherAction = (results) => ({type: 'MY_OTHER_ACTION', results});
    
    searchEpic = (action$) => 
        action$
        .ofType('SEARCH')
        .mergeMap(
            Observable
            .fromPromise(searchPromise)
            // Flattens this into two events on every search
            .mergeMap((data) => Observable.of(
              loaded(data),
              otherAction(data))
            ))
        )
    

    Note that any Rx operator that accepts an Observable also can accept a Promise, Array, or Iterable; consuming them as-if they were streams. So we could use an array instead for the same effect:

    .mergeMap((data) => [loaded(data), otherAction(data)])
    

    Which one you use depends on your personal style preferences and use case.

    0 讨论(0)
  • 2020-12-28 13:10

    Or maybe you have three actions,

    API_REQUEST, API_RUNNING, API_SUCCESS,

    searchEpic = (action$) => 
    action$
    .ofType('API_REQUEST')
    .mergeMap((action) => {
       return concat(
           of({type: 'API_RUNNING'}),
           Observable.fromPromise(searchPromise)
            .map((data) => {
              return {type: 'API_SUCCESS', data}; 
            }),
        );
    });
    
    0 讨论(0)
提交回复
热议问题