CombineLatest没有在rxjs中获取最新值

问题描述 投票:2回答:1

这是代码

const timerOne = timer(1000, 4000).pipe(
  map(x=>`1-${x}-${new Date().getSeconds()}`)
)
//timerTwo emits first value at 2s, then once every 4s
const timerTwo = timer(2000, 4000).pipe(
  map(x=>`2-${x}-${new Date().getSeconds()}`)
);
//timerThree emits first value at 3s, then once every 4s
const timerThree = timer(3000, 4000).pipe(
  map(x=>`3-${x}-${new Date().getSeconds()}`)
);

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

const subscribe = combined
.pipe(take(5))
.subscribe(
  ([timerValOne, timerValTwo, timerValThree]) => {   
    console.log(
     ` ${timerValOne},
    ${timerValTwo},
     ${timerValThree}`
    );
  }
);

这是rxjs中combineLatest()的定义

在每个observable发出至少一个值之前,不会发出初始值。

现在从上面的定义来看,输出应该是

1-2-56,
2-1-57,
3-0-58

代替

1-0-56,
2-0-57,
3-0-58

因为,我们只会在3秒之后得到timerThree Observable的值,当时timerOne的最新值为2,而timerTwo的最新值为1,我错过了什么,请帮助,谢谢

rxjs6 combinelatest
1个回答
1
投票

您的计时器将首先以[1s,2s,3s]发射,并将以4s的速率继续发射。

因此,所有流将首次发射时为3秒。

combineLatest上的下一个事件(当所有流已经发出并且任何流发出新事件时)是:5s,6s,7s ......

下面是一个插图

const timerOne = timer(100, 400);
const timerTwo = timer(200, 400);
const timerThree = timer(300, 400);
combineLatest(timerOne, timerTwo, timerThree, (...arr)=>arr.join('-'));

timer with combineLatest illustration

这是combineLatest with timers的游乐场

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.