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]) => {
}
2
Answers
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
and usemap
to build a new array/object that includes your derived value:Here is a StackBlitz that shows the problem and solutions.
Since you didn’t specify what
anotherObservable
contains and how it behaves its hard to say how to best combine the values. But one idea is to split the combination of observables into two steps:firstObs$
result together withobservableSumOperation
calculated$
withanotherObservable$
:Note that
combineLatest
will only fire as soon as every observable emits at least once. So ifanotherObservable$
does not emit a value, you will not enter the subscribe method