【问题标题】:Fire multiple actions and wait for them to resolve RxJS / Redux Observables触发多个操作并等待它们解析 RxJS / Redux Observables
【发布时间】:2023-04-05 08:39:01
【问题描述】:

我有一个动作,我想用它来初始化我的应用程序,我想为这个动作创建一个史诗,然后在这个动作的后面触发多个其他动作,等待它们全部完成,然后再触发另一个动作。我查看了其他问题,它与one

非常相似

我已经尝试过这种方法,但对我来说,它不起作用,它会触发 APP_INIT 操作,但随后无法触发序列中的任何其他操作。有人可以帮忙吗?

import { of } from 'rxjs';
import { mergeMap, zip, concat, mapTo } from 'rxjs/operators';
import { ofType } from 'redux-observable';
import { firstAction, secondAction } from 'actions';

export default function appInit (action$) {
  return (
    action$.pipe(
      ofType('APP_INIT'),
      mergeMap(() =>
        concat(
          of(firstAction()),
          of(secondAction()),
          zip(
            action$.ofType('ACTION_ONE_COMPLETE'),
            action$.ofType('ACTION_TWO_COMPLETE')
          ).mapTo(() => console.log('complete'))
        )
      )
    )
  );
}

【问题讨论】:

  • 你说 INIT 动作,但在你的例子中你有 APP_INIT
  • 只是一个错字,我会更新。 APP_INIT 动作正在触发,我可以在 Redux 开发工具中看到这一点,但在那之后它什么也没做

标签: javascript redux rxjs rxjs6 redux-observable


【解决方案1】:

原来我的代码在第一个实例中几乎没问题,主要原因是我从 rxjs/operators 导入 concat 而我应该直接从 rxjs 导入,我花了几个小时才意识到但是现在可以了。

下面的完整代码可以帮助任何人。

import { of, concat, zip } from 'rxjs';
import { mergeMap, map, take } from 'rxjs/operators';
import { ofType } from 'redux-observable';

import { appInitialisationComplete, APP_INITIALISATION } from 'client/actions/app/app';
import { actionOne, ACTION_ONE_COMPLETE } from 'client/actions/action-one/action-one';
import { actioTwo, ACTION_TWO_COMPLETE } from 'client/actions/action-two/action-two';

/**
 * appInitialisationEpic
 * @param  {Object} action$
 * @return {Object}
 */
export default function appInitialisationEpic (action$) {
  return (
    action$.pipe(
      ofType(APP_INITIALISATION),
      mergeMap(() =>
        concat(
          of(actionOne()),
          of(actioTwo()),
          zip(
            action$.ofType(ACTION_ONE_COMPLETE).pipe(take(1)),
            action$.ofType(ACTION_TWO_COMPLETE).pipe(take(1))
          )
            .pipe(map(() => appInitialisationComplete()))
        )
      )
    )
  );
}

【讨论】:

  • 好极了!同样在这里!!!我正在做同样的事情“开火行动并等待行动回来”。然后在读完这篇文章后,我意识到我还从rxjs/operators 导入了concat。如果一个是错误的,为什么两个包中都有一个?非常感谢分享这个解决方案。
【解决方案2】:

combineLatest 是你想要的,它只会在所有可观察对象都发出后才会发出。

const { combineLatest, of } = rxjs;
const { delay } = rxjs.operators;

combineLatest(
  of(1),
  of(2).pipe(delay(2000)),
  of(3).pipe(delay(1000))
).subscribe(([a,b,c]) => {
  console.log(`${a} ${b} ${c}`); // Will take 2 seconds as that is when all have emitted
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

【讨论】:

    猜你喜欢
    • 2018-04-03
    • 1970-01-01
    • 2017-05-18
    • 2021-12-01
    • 2017-10-15
    • 2019-05-31
    • 2018-08-03
    • 1970-01-01
    相关资源
    最近更新 更多