Home > OS >  How can I avoid nested subscribe in rxjs?
How can I avoid nested subscribe in rxjs?

Time:01-11

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?

CodePudding user response:

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();
      });

CodePudding user response:

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

switchMap is usually when the second call depends on the result of the first call, which is why you would nest as well but your call seem like they are not dependent so you could just use forkJoin

forkJoin(this.someService.call1(), this.ticketService.getListOfTickets()).subscribe(
  ([data, listOfTickets]) => {
    const { game, prizes } = data;
    this.ticketService.setListOfTickets(game.tickets);
    this.listOfTickets = listOfTickets;
    this.game = game;
    this.type = game.type;
    this.combinations = prizes.map((el: Prize) => el.patterns).flat();
  }
)
  • Related