Timothy
Timothy

Reputation: 3593

RxJS withLatestFrom skips initial Subject value

In the following example, for whatever reason, initial value is ignored.

const frameRateSubject: BehaviorSubject<number> = new BehaviorSubject(24);
const loadedMetadata$: Observable<Event> = fromEvent(this.videoElement, 'loadedmetadata');

frameRateSubject.asObservable()
  .pipe(
    withLatestFrom(loadedMetadata$), // by commenting out this line, both 24 and 20 values are received
    tap(([frameRate]: [number, Event]) => {
      // initial value of 24 is never received, why is it?
      console.log('frameRateSubject', frameRate)
    })
  )
  .subscribe();

setTimeout(() => {
  frameRateSubject.next(20)
}, 10000)

Any ideas why?

Upvotes: 0

Views: 216

Answers (1)

Matthieu Riegler
Matthieu Riegler

Reputation: 54698

withLatestFrom combines the source observable (here frameRateSubject$) with other streams (loadedMetadata$) and emits values calculated from the latest values of each, only when the source emits.

But in your case loadedMetadata$ hasn't emitted when frameRateSubject$ emits 24. So the value is skipped.

CombineLatest is most likely the operator you are looking for here.

Upvotes: 4

Related Questions