1

On my

ngOnInit()

I have this code:

combineLatest([ obs1, obs2, obs3]).subscribe(([obs1Res, Obs2Res, Obs3Res]) => { })

and the result is emitted once when they are completed.

Is there a way to emit for each new completed observable and get a result like so:

[null, 2, null], [1, 2, null], [1, 2, 3]

I will use this to dynamically render a page and assign the values if they are not null.

combineLatest([obs1, obs2, obs3]).subscribe(([obs1Res, Obs2Res, Obs3Res]) => {firstValue ??= Obs1Res; secondValue ??= Obs2Res; thirdValue ??= Obs3Res })
N. St
  • 15
  • 2

2 Answers2

0

combineLastest will combine all the latest values for any emit from any of the observables. if you want all the latest from all the observables then you can use zip().

There could be a different solution for what you want. Use this visual representation for what you want from your subscription: https://rxmarbles.com/

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
Sandeep Kumar
  • 2,397
  • 5
  • 30
  • 37
0

and the result is emitted once when they are completed

With combineLatest the first emission will occur after each source emits at least one value. Then, after that an emission with occur when any of the sources emit.

If your goal is to receive null for those that haven't emitted yet, you an use startWith to provide an initial emission for each source:

combineLatest([ 
  obs1.pipe(startWith(null)), 
  obs2.pipe(startWith(null)), 
  obs3.pipe(startWith(null)),
]).subscribe(
  ([obs1Res, Obs2Res, Obs3Res]) => { }
);

This will provide you with almost the output you desire:

[null, null, null], [null, 2, null], [1, 2, null], [1, 2, 3]

To prevent the initial [null, null, null] emission, you can use skip:

combineLatest([ 
  obs1.pipe(startWith(null)), 
  obs2.pipe(startWith(null)), 
  obs3.pipe(startWith(null)),
]).pipe(skip(1)).subscribe(
  ([obs1Res, Obs2Res, Obs3Res]) => { }
);
BizzyBob
  • 12,309
  • 4
  • 27
  • 51