我有一个动作要用于初始化我的应用程序,我想为此动作创建一个史诗,然后从其背后触发多个其他动作,等待它们全部完成,然后触发另一个动作。我看了其他问题,它和这个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'))
)
)
)
);
}
答案 0 :(得分:2)
结果证明,我的代码一开始就还可以,主要原因是我本应该直接从concat
导入时从rxjs/operators
导入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()))
)
)
)
);
}
答案 1 :(得分:0)
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>