How to return different values from the same observable without multiple calls? I intend to subscribe just one time the firstObs$, but return the values and sumFromValues.
combineLatest([
this.firstObs$,
this.firstObs$.pipe(
switchMap(someOperation => {
return this.observableSumOperation(someOperation.first, someOperation.second)
})
),
this.anotherObservable$,
])
.subscribe(([values, sumFromValues, anotherValues]) => {
}
As you've noticed, when you include the same source observable inside of combineLatest
, the "combinelatest observable" will emit multiple times. Generally this is not desirable.
I can think of two solutions for this:
debounceTime(0)
to suppress emissions that occur in the same event loop:combineLatest([
firstObs$,
firstObs$.pipe(map(({first, second}) => first + second)),
anotherObservable$,
])
.pipe(debounceTime(0));
combineLatest
and use map
to build a new array/object that includes your derived value:combineLatest([
firstObs$,
anotherObservable$,
])
.pipe(
map(([values, anotherValues]) => [
values,
values.first + values.second,
anotherValues
])
);
Here is a StackBlitz that shows the problem and solutions.