#Pipe Observable Stream To Make Request For Each Item?

1 messages · Page 1 of 1 (latest)

shadow wyvern
#

Hello. I am trying to do something as follows:

I have a function that returns an observable that emits an array of items, and then with each of these items I want to make an additional request based on a property in said thing that also returns an observable, then combine the two items and subscribe to the result (sorry if this explanation is a little confusing, I'd be happy to elaborate)

here is what ive tried so far but to no avail:

        this.gameService
            .fetchGames()
            .pipe(
                switchMap((ret: any) => ret.map((game: any) => this.userService.getUserById(game.hostId)))
            )
            .subscribe((e) => {
                console.log("result:", e);
            });
#

basically I want the final structure to be transformed as follows:

[{ hostId: 123, foo: true, bar: false }, { hostId: 1234, foo: true, bar: false }}
[{ hostId: 123, foo: true, bar: false, host: {...} }, { hostId: 1234, foo: true, bar: false, host: {...} }]

#

where in host comes from another observable (http request)

woeful hinge
#
  1. Don't use any
  2. the function passed to switchMap() is supposed to return an observable. But it returns an array of observables. So you need to decide hos to combine them: forkJoin? concat? merge? something else?
    Your method could look like this:
this.gameService.fetchGames().pipe(
  switchMap((games: Array<Game>) => {
    const gamesWithHost: Array<Observable<GameWithHost> = games.map((game: Game) => this.userService.getUserById(game.hostId).pipe(map((host: Host) => ({ ...game, host)));
    return forkJoin(...gamesWithHost);
  })
).subscribe((e: Array<GameWithHost>) => console.log("result:", e));
shadow wyvern
#

ah, forkJoin makes a lot of sense

#

(only using any because my backend dev changes the return types every 5 minutes lol)

#

ill give this a shot

#

works like a charm. thanks a lot!! @woeful hinge