0
votes

I have an array of objects where the object has a field which is of type Observable but there is another field of boolean. I want to create a single subscription that listens to those observables but uses the boolean field and not the observable value.

To be more specific, I'm using angular and have an array of FormControl. I'm listening to the valueChanges event but need to map it to an array of boolean using the isValid field.

I've tried mapping the observable with combineLatest but when there is more than one object, it never works.

Observable.combineLatest(this.controls.map(c => c.valueChanges!.map(sc => c.valid))).subscribe(validations => { console.log('fired'); });

in the example, 'fired' is only logged when I have a single control. As soon as I add another control to the list, it doesn't work.

1

1 Answers

1
votes

combineLatest only emits when all of the underlying Observables have emitted at least once (so your example works as expected when there is a single FormControl, but otherwise nothing will happen until all FormControls undergo a state change)

A quick fix might be to use startWith:

Observable.combineLatest(
  this.controls.map(c => c.valueChanges!.map(sc => c.valid).startWith(true))
).subscribe(validations => {
  console.log('fired');
});

Be aware that with this code you'll get a single starting emission with all validations true