【问题标题】:RXJS: Subscription to share operator causes strange behaviourRXJS:订阅共享运算符会导致奇怪的行为
【发布时间】:2019-06-23 08:10:11
【问题描述】:

使用这些 RxJS 工具:BehaviorSubject、Subscribe 和 Next

请参考此代码框,并查看控制台以查看视觉效果:https://codesandbox.io/s/fancy-bird-0m81p

你会注意到订阅中的对象“C”值是“1 stream behind

考虑以下代码:

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 发生在“之前”

我相信codesandox会说明并使其更加清晰。

我如何保持正确的事件顺序,以便最新更新出现在订阅的最后?

【问题讨论】:

    标签: rxjs rxjs6


    【解决方案1】:

    目前解决此问题的一种非理想方法是将下一条语句包含在订阅中的超时中。如果有人有更好的解决方案,请发帖。

    StoreUpdates$.pipe(
      distinctUntilChanged((p, n) => {
        return p.b === n.b;
      })
    ).subscribe(store => {
      setTimeout(() => {
        Store$.next({ c: Math.random() });
      },0)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      • 2018-07-28
      相关资源
      最近更新 更多