Vladimir
Vladimir

Reputation: 31

How can I avoid nested subscribe in rxjs?

I have an code with nested subscribes:

      .subscribe((data) => {
        const { game, prizes } = data;
        this.ticketService.setListOfTickets(game.tickets);
        this.ticketService.getListOfTickets().subscribe((data: any) => {
          this.listOfTickets = data;
        });
        this.game = game;
        this.type = game.type;
        this.combinations = prizes.map((el: Prize) => el.patterns).flat();
      });

How can i improve this code to avoid nested subscription?

Upvotes: 0

Views: 71

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21658

.pipe(
    switchMap(data => {
      this.ticketService.setListOfTickets(data.game.tickets);
      return this.ticketService.getListOfTickets().pipe(
        map(listOfTickets => ({ ...data, listOfTickets }))
      );
    })
)
.subscribe(({ game, prizes, listOfTickets }) => {
    this.listOfTickets = listOfTickets;
    this.game = game;
    this.type = game.type;
    this.combinations = prizes.map((el: Prize) => el.patterns).flat();
});

switchMap takes the result of the firstCall and uses the result to switch to an inner observable.

Upvotes: 1

AvgustinTomsic
AvgustinTomsic

Reputation: 1841

You can use forkJoin and join multiple calls into single subscription. From your code is not visible the name of the function that are you subscribing on, so I just used name: gameService.getGames()

forkJoin([this.gameService.getGames(),this.ticketService.getListOfTickets()]).subscribe((data) => {
        const { game, prizes } = data[0];
        this.ticketService.setListOfTickets(game.tickets);
        this.listOfTickets = data[1];
        this.game = game;
        this.type = game.type;
        this.combinations = prizes.map((el: Prize) => el.patterns).flat();
      });

Upvotes: 0

Related Questions