In our Angular application, we have a method that combines the results of 3 APIs into a single list.
loadPlaces$ = this.actions$.pipe(
ofType(PlaceActionTypes.LOAD_PLACES),
switchMap((action: LoadPlaces) =>
from(this.service.findAreas()).pipe(
switchMap(async (areas: Area[]) => {
try {
const places: Place[] = await Promise.all(
areas.map(async (area: Area) => {
const [residential, commercial] = await Promise.all([
this.service.getResidentials(area.id),
this.service.getCommercial(area.id),
]);
return new Place(area, residential, commercial);
})
);
return new LoadPlacesSuccess(places);
} catch (error) {
return new LoadPlacesFail(error);
}
}),
catchError((error) => of(new LoadPlacesFail(error)))
)
)
);
We fetch all available areas and create a Place
object for each one, containing information about the area along with residential and commercial data.
This results in an array of Place
objects, each with nested data.
Our goal is to transition from using promises to using observables exclusively.
I am struggling to convert my current setup to use observable chains only. While I was able to retrieve both residential and commercial data simultaneously using combineLatest, I faced challenges when mapping over the areas array. It's crucial to handle nested subscriptions for each area without explicitly calling .subscribe()
.
How can I implement a nested combineLatest subscription for "each item"?
I experimented with a combination of from(), switchMap(), and combineLatest() but could not achieve the desired outcome. I kept getting arrays of observables instead of actual values.