Reputation: 6926
How can I combine the following subscriptions into one?
this.form.get("type").valueChanges.subscribe(() => {
this.calcFinalTransports();
})
this.form.get("departure").valueChanges.subscribe(() => {
this.calcFinalTransports();
})
this.form.get("destination").valueChanges.subscribe(() => {
this.calcFinalTransports();
})
this.form.get("stations").valueChanges.subscribe(() => {
this.calcFinalTransports();
})
Upvotes: 18
Views: 14988
Reputation: 631
The accepted answer on this related question shows to get the combineLatest
to emit when not all of the added observables have emitted a value yet. This works great when your form controls are initialized with values of undefined
.
RxJS combineLatest without waiting for source observables to emit?
combineLatest([
source1$.pipe(startWith(undefined)),
source2$.pipe(startWith(undefined)),
])
Upvotes: 0
Reputation: 105489
You have a few choices depending on what output you expect. You may want to read this article:
If you just want to get notified whenever any of the value changes use merge
:
import {merge} from "rxjs/observable/merge";
merge(
this.form.get("type").valueChanges,
this.form.get("departure").valueChanges,
this.form.get("destination").valueChanges
this.form.get("stations").valueChanges
).subscribe(() => this.calcFinalTransports());
Upvotes: 20
Reputation: 1118
If want to use single Data observable pattern and combine multiple observables into one observable, then combineLatest may come as useful.
PesudoCode
userNameAndEmail$=this.userNameAndEmail().pipe(startsWith(null));
userAddressDetail$=this.userAddressDetails().pipe(startsWith(null));
userMiscDetails$=this.userMiscDtls();
completeUserData$=combineLatest([userNameAndEmail$,userAddressDetail$,userMiscDetails$])
.pipe(map(([userNameAndEmail,userAddressDetail,userMiscDetails])=>{
return {userNameAndEmail,userAddressDetail,userMiscDetails}; } ));
However, there are certain conditions. https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest
Upvotes: 2