RXJS how to optimize a ForEach in a nested subscribe?

Viewed 31

I'm rather new to observables and still learning and i need some help. I have a slider with some campaigns and for each campaign i have a producer which i need get and set to the campaign.

I know that using pipe, merge and MergeMap here is probably some of the solution but i can't seem to get it to work, does anyone have an idea for me?

This is what i currently have.

  fetchCampaigns() {
    this.loading = true;
    this.campaignService
      .getCampaigns(
        this.campaignAmount,
        this.sorting,
        this.desc
      )
      .subscribe(
        campaignListDto => {
          this.campaigns = campaignListDto;
          this.campaigns.map(campaign => {
            this.producerService.getProducerByName(campaign.producer_name)
              .subscribe((producer) => {
                campaign.producer = producer
                campaign.producer_name
              })
            })
            this.loading = false; 
            this.fetchProducerMinPrices();
            this.fetchProducerTotalCampaigns();
        })
  };
1 Answers

Try:

fetchCampaigns() {
  this.loading = true;
  this.campaignService.getCampaigns(this.campaignAmount,this.sorting,this.desc).pipe(
    switchMap(campaignListDto => forkJoin(campaignListDto.map(
      campaign => this.producerService.getProducerByName(campaign.producer_name).pipe(
        map(producer => ({ ...campaign, producer })),
      ),
    ))),
  ).subscribe(campaignListDtoExtended => {
    this.campaigns = campaignListDtoExtended;
    this.loading = false; 
    this.fetchProducerMinPrices();
    this.fetchProducerTotalCampaigns();
  });
}
Related