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();
})
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());
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With