I'm having difficulty wrapping my head around why combineLatest
isn't returning the latest value. This example is a bit contrived but at least it illustrates my problem. Notice the value of color
from the combineLatest
observable returns a previous value, when the subject.value
is correct. It's like the color$
observable hasn't emitted.
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'
});
Actual Output
{color: "red"} "red" "red"
{color: "yellow"} "red" "yellow"
{color: "yellow"} "yellow" "yellow"
Expected Output
{color: "red"} "red" "red"
{color: "yellow"} "yellow" "yellow" // Notice middle value is yellow
{color: "yellow"} "yellow" "yellow"
https://stackblitz.com/edit/combine-latest-issue
If someone could help explain whats going, and provide a workaround or proper way to think about this in rxjs
I would appreciate it.
It may be useful to visualize what is going on rather than words:
main$ R--------------------Y------------------------------
color$ -------R-----------------------Y---------------------
output -----[R,R]---------[Y,R]-----[Y,Y]------------------
If you use zip
instead of combineLatest
, you will get very closer to what you expect. See bellow what happens if you use zip
:
main$ R--------------------Y------------------------------
color$ -------R-----------------------Y---------------------
output -----[R,R]-------------------[Y,Y]------------------
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With