combineLatest不会发出最新值

时间:2018-04-18 22:56:47

标签: rxjs rxjs5

我很难绕过为什么combineLatest没有返回最新值。这个例子有点做作,但至少它说明了我的问题。请注意,当color正确时,combineLatest observable中subject.value的值会返回先前的值。它就像color$可观察到的那样没有被发射出来。

import { map, distinctUntilChanged, combineLatest } from 'rxjs/operators'
import { Observable } from 'rxjs/observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

const main$ = new BehaviorSubject({color: 'red'});

const color$ = main$.pipe(
  map(state => state.color),
)

main$.pipe(
  combineLatest(color$)
)
.subscribe(([state, color]) => {
  console.log(state, color, main$.value.color);
})

main$.next({
    color: 'yellow'
});

实际输出

{color: "red"} "red" "red"

{color: "yellow"} "red" "yellow"

{color: "yellow"} "yellow" "yellow"

预期输出

{color: "red"} "red" "red"

{color: "yellow"} "yellow" "yellow"  // Notice middle value is yellow

{color: "yellow"} "yellow" "yellow"

https://stackblitz.com/edit/combine-latest-issue

如果有人可以帮助解释最新情况,并在rxjs中提供解决方法或正确的方法来考虑这一点,我将不胜感激。

3 个答案:

答案 0 :(得分:4)

可视化正在发生的事情而非文字可能是有用的:

main$     R--------------------Y------------------------------

color$    -------R-----------------------Y---------------------

output    -----[R,R]---------[Y,R]-----[Y,Y]------------------

如果您使用zip代替combineLatest,您将更接近您的期望。如果您使用zip

,请参阅下面的内容
main$     R--------------------Y------------------------------

color$    -------R-----------------------Y---------------------

output    -----[R,R]-------------------[Y,Y]------------------

答案 1 :(得分:1)

第一个main$已更新,它会作为更改提供给combineLatest(),但不会触发输出,因为color$尚未发出值。然后color$计算其新值,发出它,现在有combineLatest()可用的两个值,并输出第一行文本。

然后main$更新为{color: "yellow"},并将combineLatest()提供给main$,其中color$的最新值和"red"的最新值(即仍为{color: "yellow"} "red" "yellow",并触发color$的新输出。

最后,combineLatest()已更新并触发{{1}}以发出最后一行输出。

答案 2 :(得分:0)

使用Observable.zip而不是CombineLatest,它会从主题中发出非常接近的值。它按预期对我有用。

相关问题