Picture this: I have an observable that gives me chocolate cookies, but I only want to eat the ones without white chocolate. Since I am blind, I need to send them to a service to determine if they are white or not. However, I don't receive the answer immediately. Instead of waiting, I would prefer another observable.
Here is the code I ended up with, but I find it quite cumbersome and believe there must be a simpler and more elegant solution:
// Transform the observable
chocolateCookieObservable$.pipe(
// Using switchMap to create a new stream that combines...
switchMap((chocolateCookie: ChocolateCookie) => combineLatest(
// An artificial stream with just one cookie...
of(chocolateCookie),
// And the answer from my cookie service (also an observable)
this.chocolateCookieService
.isChocolateCookieWithWhiteChocolate(chocolateCookie),
// This results in an observable array containing both elements
)),
// Filtering the resulting observable array based on whether the cookie is white or not
filter(([chocolateCookie, isWhite]: [ChocolateCookie, boolean]) => !isWhite),
// Mapping the array to discard the boolean value, leaving only the filtered cookies
map(([chocolateCookie]: [ChocolateCookie, boolean]) => chocolateCookie),
).subscribe((chocolateCookie: ChocolateCookie) => {
this.eat(chocolateCookie);
}
Although this approach works reasonably well, it can become confusing when dealing with nested scenarios. Is there a direct way to filter or map the observable to obtain the required information without employing the combineLatest-of combination?