试图让一个事件用初始事件数据触发多个switchMap。
每个动作都会创建对某些转换的承诺,然后将其写入文件系统。这些动作是独立且无关的,但是使用相同的数据只是出于不同的目的,因此不应将其合并。
当前使用水龙头而不是switchMap,这可能导致多个事件同时运行。
const SomeApiCall = () => {return {some: 'data'} }
const AllowsDoAction = () => {console.log('Parsing API and writting some things to FS -- PLACEHOLDER')}
const SomeTimeDoThisActionTo = () => {console.log('Parsing API and writting some other things to fs, by asking more data from the API and first, so it is long thing to do, so a new event can arrive first -- PLACEHOLDER')}
const deepEqual = (prev, cur) => prev === cur // normally a proper deepEqual...
const taps = [tap(AllowsDoAction)];
if (someCondition) taps.push(SomeTimeDoThisActionTo)
const observable = timer(0, 500).pipe(
exhaustMap(SomeApiCall),
distinctUntilChanged((prev, cur) => deepEqual(prev, cur))
...taps
);
答案 0 :(得分:0)
我将返回文件系统写入 observables(编辑2)
const SomeApiCall = () => {
return of({ some: 'data' });
};
const AllowsDoAction = () => {
console.log('Parsing API and writting some things to FS -- PLACEHOLDER');
return timer(100).pipe(map(() => 'write 1 finished'));
};
const SomeTimeDoThisActionTo = () => {
console.log(
'Parsing API and writting some other things to fs, by asking more data from the API and first, so it is long thing to do, so a new event can arrive first -- PLACEHOLDER'
);
return timer(1000).pipe(map(() => 'write 2 finished'));
};
然后使用concatMap等待所有文件系统操作完成。
const deepEqual = (prev, cur) => prev === cur; // normally a proper deepEqual...
const taps = [(AllowsDoAction)];
const someCondition = true;
if (someCondition) {
taps.push(SomeTimeDoThisActionTo);
}
const reduxStorageEvent$ = of('replace this with real event');
const observable = merge(timer(0, 500), reduxStorageEvent$).pipe(
exhaustMap(SomeApiCall),
distinctUntilChanged((prev, cur) => deepEqual(prev, cur)),
// use switchMap to cancel previous writes (edit 2)
// await latest write operations, before starting new writes
concatMap((someData) => {
const writes = taps.map((tapFx) => {
return tapFx(someData);
});
// wait for all writes
return forkJoin(...writes);
})
);
concatMap就像一个队列。此队列中的第一个必须先完成,然后才能开始。