我有一个关于 RxJS combineLatest 运算符的查询。我已经修改了给出的例子

https://www.learnrxjs.io/operators/combination/combinelatest.html

如下:

//timerOne emits first value at 1s, then once every 4s
const timerOne = Rx.Observable.timer(1000, 4000);
//timerTwo emits first value at 2s, then once every 4s
const timerTwo = Rx.Observable.timer(2000, 4000)
//timerThree emits first value at 3s, then once every 4s
const timerThree = Rx.Observable.of(false);

//when one timer emits, emit the latest values from each timer as an array
const combined = Rx.Observable
.combineLatest(
    timerOne,
    timerTwo,
    timerThree
);

const subscribe = combined.subscribe(latestValues => {
    //grab latest emitted values for timers one, two, and three
    const [timerValOne, timerValTwo, timerValThree] = latestValues;


  if(latestValues[0] === 3) {
    this.timerThree = Rx.Observable.of(true);
  }

  console.log(
    `Timer One Latest: ${timerValOne},
     Timer Two Latest: ${timerValTwo},
     Timer Three Latest: ${timerValThree}`
   );
});

我希望 timerThree 的值更改为 true 位它总是继续打印 false 如输出片段所示:
"Timer One Latest: 3,
 Timer Two Latest: 2,
 Timer Three Latest: false"
"Timer One Latest: 3,
 Timer Two Latest: 3,
 Timer Three Latest: false"
"Timer One Latest: 4,
 Timer Two Latest: 3,
 Timer Three Latest: false"

知道为什么会这样吗?有没有什么办法解决这一问题?谢谢

最佳答案

这里需要注意的重要一点是 timerThree 本身并不是一个可观察的对象,而是一个对可观察对象的引用。当您使用 combineLatest 时,它​​正在组合该对象,而不是引用它的变量。因此,当您将 timerThree 分配给一个新的 observable 时,它​​现在指向一个新对象,但 combined 仍在使用旧对象。

如果您希望能够更改 timerThree 的值,请尝试使用 Subject 代替。然后您可以使用 timerThree.next 向其推送新值。

关于javascript - RxJS combineLatest 操作符奇怪的行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45765362/

10-10 16:06