RXJS:订阅共享运算符会导致奇怪的行为
RXJS: Subscription to share operator causes strange behaviour
使用这些 RxJS 工具:BehaviorSubject、Subscribe 和 Next
请参考这个codesandbox,查看console可以看到一个视觉效果:https://codesandbox.io/s/fancy-bird-0m81p
您会注意到订阅中的对象 "C" 值为“落后 1 个流
考虑以下代码:
const initialState = { a: 1, b: 2, c: 3 };
const Store$ = new BehaviorSubject(initialState);
const StoreUpdates$ = Store$.pipe(
scan((acc, curr) => {
return Object.assign({}, acc, curr);
}, initialState),
share()
);
export const updateStore = update => {
Store$.next(update);
};
StoreUpdates$.pipe(
distinctUntilChanged((p, n) => {
return p.b === n.b;
})
).subscribe(store => {
Store$.next({ c: Math.random() });
});
StoreUpdates$.subscribe(store => {
console.log("Subscription Check:: Notice issue here", store);
});
当您调用 updateStore 函数时,在 console.log 中您会注意到 C 值(在订阅内的下一次调用中更新)出现在第一次迭代中,而旧值出现在最后一次迭代。所以不知何故它看起来订阅中的 next.call 发生 "Before"
我相信codesandox会说明并使其更加清晰。
如何保持事件的正确顺序以便最新更新显示在订阅的最后?
目前,解决此问题的 non-ideal 方法是在超时时间内将下一条语句包装在订阅中。如果有人有更好的解决方案,请post.
StoreUpdates$.pipe(
distinctUntilChanged((p, n) => {
return p.b === n.b;
})
).subscribe(store => {
setTimeout(() => {
Store$.next({ c: Math.random() });
},0)
});
使用这些 RxJS 工具:BehaviorSubject、Subscribe 和 Next
请参考这个codesandbox,查看console可以看到一个视觉效果:https://codesandbox.io/s/fancy-bird-0m81p
您会注意到订阅中的对象 "C" 值为“落后 1 个流
考虑以下代码:
const initialState = { a: 1, b: 2, c: 3 };
const Store$ = new BehaviorSubject(initialState);
const StoreUpdates$ = Store$.pipe(
scan((acc, curr) => {
return Object.assign({}, acc, curr);
}, initialState),
share()
);
export const updateStore = update => {
Store$.next(update);
};
StoreUpdates$.pipe(
distinctUntilChanged((p, n) => {
return p.b === n.b;
})
).subscribe(store => {
Store$.next({ c: Math.random() });
});
StoreUpdates$.subscribe(store => {
console.log("Subscription Check:: Notice issue here", store);
});
当您调用 updateStore 函数时,在 console.log 中您会注意到 C 值(在订阅内的下一次调用中更新)出现在第一次迭代中,而旧值出现在最后一次迭代。所以不知何故它看起来订阅中的 next.call 发生 "Before"
我相信codesandox会说明并使其更加清晰。
如何保持事件的正确顺序以便最新更新显示在订阅的最后?
目前,解决此问题的 non-ideal 方法是在超时时间内将下一条语句包装在订阅中。如果有人有更好的解决方案,请post.
StoreUpdates$.pipe(
distinctUntilChanged((p, n) => {
return p.b === n.b;
})
).subscribe(store => {
setTimeout(() => {
Store$.next({ c: Math.random() });
},0)
});