RxJS 和 redux-observable:延迟(时间)在 mapTo() 之后没有正确应用

RxJS and redux-observable: delay(time) is not applied correctly after mapTo()

我正在尝试使用 payload.type = 'observable' 发送 'SET_MIDDLEWARE_TYPE' 操作,等待 5 秒,然后进行 API 调用。当前,SET_MIDDLEWARE_TYPE 操作未被调度。如果我删除延迟和 mergeMap,它会调度该操作。

预计: FETCH_USER_WITH_OBSERVABLE_REQUEST --> SET_MIDDLEWARE_TYPE(等待 5 秒)--> FETCH_USER_WITH_OBSERVABLE_SUCCESS

实际: FETCH_USER_WITH_OBSERVABLE_REQUEST --> (等待 5 秒) --> FETCH_USER_WITH_OBSERVABLE_SUCCESS

如何获得预期的行为?

代码:

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;

您在执行 mergeMap 时放弃了 SET_MIDDLEWARE_TYPE 操作。请注意您传递给 mergeMap 的参数 action?除非你传播它,否则它不能使它进一步向下游发展。

您需要将其添加到传出流中。我建议您改为执行以下操作:

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;