In my project, I have implemented 3 different endpoints that return upcoming, current, and past events. The requirement is to display only the event that is the farthest in the future without making unnecessary calls to all endpoints at once. To achieve this optimization, I devised a simple RxJs stream where I call the first endpoint, and if it doesn't return any data, I proceed to the next one. Here's how the code looks:
this.eventsService.getUpcoming(id).pipe(
switchMap((upcoming) => {
if (upcoming.length) {
return of(upcoming);
}
return this.eventsService.getCurrent(id).pipe(
switchMap((current) => {
if (current.length) {
return of(current);
}
return this.eventsService.getPast(id)
})
);
}),
// other transformation operators such as map, etc.
Is there a way to avoid nesting switch maps within each other?