There are two input fields on my form: Street address and Zipcode. Each field emits its value on keyup as a Subject in Angular.
Before calling an API endpoint with these values, I need to ensure that both the street address and zip code values are valid.
For the street address observable:
this.searchableComponent.value
.do((value: any) => {
if (value.length < this.MINIMAL_LENGTH_FOR_SEARCH) {
this.suggestions = [];
}
})
.filter(() => this._zipcodeModel !== undefined && this._zipcodeModel.city.length > 0)
.filter((value: any) => value.length >= this.MINIMAL_LENGTH_FOR_SEARCH)
.debounceTime(this.DEBOUNCE_TIME_IN_MS)
.distinctUntilChanged()
.do(() => console.log('ready street address'))
For the zip code observable:
this.zipcodeInput.value
.filter((value: string) => {
const pattern = new RegExp(US_ZIPCODE);
return pattern.test(value);
})
.distinctUntilChanged()
.mergeMap((zipcode: string) => this.addressService.lookup(zipcode))
.map((zipcodeModel: ZipcodeModel) => this._zipcodeModel = zipcodeModel)
.do(() => console.log('ready zipcode'))
Testing with a simple forkJoin
(same as combineLatest attempt):
forkJoin(this.searchableComponent.value, this.zipcodeInput.value)
.subscribe((results: any) => {
console.log(results)
})
I attempted to use forkJoin
on both observables, but it seems that neither of them emitted anything. When I tried using combineLatest
after the first observable was valid and complete, the combination of them completed on every emission of the second observable, even if it was invalid.
What is the correct approach to ensure completion of multiple observables only when all of them are completed and valid?