触发多个动作并等待它们解析 RxJS/Redux Observables [英] Fire multiple actions and wait for them to resolve RxJS / Redux Observables
问题描述
我有一个动作,我想用它来初始化我的应用程序,我想为这个动作创建一个史诗,然后在这个动作的后面触发多个其他动作,等待它们全部完成,然后再触发另一个动作.我查看了其他问题,它与此非常相似 一个
I have an action that I want to use to initialise my app, I want to create an epic for this action and then fire multiple other actions off the back of this, wait for them to all complete and there fire another action. I had a look at other questions and it's pretty similar to this one
我已经尝试过这种方法,但对我来说,它不起作用,它会触发 APP_INIT
操作然后但未能触发序列中的任何其他操作.有人可以帮忙吗?
I've tried this approach and for me, it doesn't work, it fires the APP_INIT
action then but then fails to fire any of the other actions in the sequence. Is anyone able to help?
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'))
)
)
)
);
}
推荐答案
结果我的代码一开始还不错,主要原因是我从 导入了
当我应该直接从 concat
rxjs/operatorsrxjs
导入时,我花了几个小时才意识到,但现在它可以工作了.
Turns out my code was pretty much okay in the first instance, the main cause was that I was importing concat
from rxjs/operators
when I should have been importing from rxjs
directly, it took me hours to realise but it now works.
下面的完整代码,可能对任何人都有帮助.
Full code below for anyone that it might help.
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/Redux Observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!