1

I am trying to dispatch 'SET_MIDDLEWARE_TYPE' action with payload.type = 'observable', wait 5 seconds and then make an API call. Currently, the SET_MIDDLEWARE_TYPE action is not being dispatched. If I remove the delay and the mergeMap, it dispatch that action.

Expected: FETCH_USER_WITH_OBSERVABLE_REQUEST --> SET_MIDDLEWARE_TYPE (wait 5 seconds) --> FETCH_USER_WITH_OBSERVABLE_SUCCESS

Actual: FETCH_USER_WITH_OBSERVABLE_REQUEST --> (wait 5 seconds) --> FETCH_USER_WITH_OBSERVABLE_SUCCESS

How can I obtained the expected behavior?

Code:

import { Observable } from 'rxjs';
import { githubApi } from './api';

const githubEpic = action$ =>
 // Take every request to fetch a user
  action$.ofType('FETCH_USER_WITH_OBSERVABLES_REQUEST')
    .mapTo(({ type: 'SET_MIDDLEWARE_TYPE', payload: { type: 'observable'} }))
    // Delay execution by 5 seconds
    .delay(5000)
    // Make API call
    .mergeMap(action => {
      // Create an observable for the async call
      return Observable.from(githubApi.getUser('sriverag'))
        // Map the response to the SUCCESS action
        .map((result) => {
        return {
          type: 'FETCH_USER_WITH_OBSERVABLES_SUCCESS',
          payload: { result } ,
        };
      });
    });

export default githubEpic;
4

1 回答 1

2

You are abandoning the SET_MIDDLEWARE_TYPE action when you perform the mergeMap. Notice the parameter that you pass into the mergeMap called action? That cannot make it any further downstream unless you propagate it.

You will need to prepend it to the outgoing stream. I suggest you do the following instead:

import { Observable } from 'rxjs';
import { githubApi } from './api';

const githubEpic = action$ =>
 // Take every request to fetch a user
  action$.ofType('FETCH_USER_WITH_OBSERVABLES_REQUEST')
    .mapTo(({ type: 'SET_MIDDLEWARE_TYPE', payload: { type: 'observable'} }))
    // Delay execution by 5 seconds
    .delay(5000)
    // Make API call
    .mergeMap(action => 
      // Async call
      Observable.from(githubApi.getUser('sriverag'))
        // Map the response to the SUCCESS action
        .map(result => ({
          type: 'FETCH_USER_WITH_OBSERVABLES_SUCCESS',
          payload: { result }
        }))
        // Prepend the original action to your async stream so that it gets 
        // forwarded out of the epic
        .startWith(action)
    );

export default githubEpic;
于 2017-01-20T19:39:42.747 回答