Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combineLatest doesn't emit latest value

Tags:

rxjs

rxjs5

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.

like image 726
cgatian Avatar asked Apr 18 '18 22:04

cgatian


1 Answers

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]------------------
like image 163
siva636 Avatar answered Sep 30 '22 07:09

siva636