I have obtained 3 different Observables from 3 separate Services through API calls:
this.gs.getLocationName().subscribe((loc) => this.locationName = loc);
this.gs.getLocationInfo(this.locationName).subscribe((data) => {
this.lat = data.results.geometry.location.lat;
this.lon = data.results.geometry.location.lng;
});
this.ws.getWeatherByCoordinates(this.lat, this.lon).subscribe((data) => ...);
Since each Observable depends on the previous one, I need to run them sequentially.
I understand how to combine 2 Observables using a pipe and mergeMap, but I face a challenge with 3 Observables.
My workaround looks like this:
this.gs
.getLocationName()
.pipe(
tap((loc) => {
this.locationName = loc;
}),
mergeMap((loc) => {
return this.gs.getLocationInfo(this.locationName);
})
)
.pipe(
tap((data) => {
this.lat = data.results[0].geometry.location.lat;
this.lon = data.results[0].geometry.location.lng;
})
)
.subscribe((data) => {
this.ws.getWeatherByCoordinates(this.lat, this.lon).subscribe((data) => ...);
});
While this solution works, I am uncertain about having a Subscription within another Subscription. My alternate approach is:
this.gs
.getLocationName()
.pipe(
tap((loc) => {
this.locationName = loc;
}),
mergeMap((loc) => {
return this.gs.getLocationInfo(this.locationName);
})
)
.pipe(
tap((data) => {
this.lat = data.results[0].geometry.location.lat;
this.lon = data.results[0].geometry.location.lng;
}),
concatMap((data) => {
return this.ws.getWeatherByCoordinates(this.lat, this.lon);
})
)
.subscribe((data: WeatherModel) => {
...
});
Although this also functions correctly, I question if it's the optimal implementation. Despite that, concatMap seems to serve its purpose for me.
Are there any recommendations on enhancing the quality of my code?