Home > Software design >  nested observables executed one after the other after termination
nested observables executed one after the other after termination

Time:11-12

i'am implementing angular solution to get all items in database first , after termination i then get the current selected box from database , then mapping the items to the box. i need that all the items are charged then getting the box at the end do the mapping , i have the following code that works but it s a litle bit dirty by doing a nested observables , any one of you have a cleaner solution?? i found on the documentation the solution os swithMap but i think that it is not appropriate to my case because a switch map does not work the upper observable to finish to execute the inner one

this.getItems().subscribe(items => {
        this.itemsInDataBase = items;
    this.loadActiveBox().subscribe(box => {
        this.selectedBox= box;

        this.selectedBox?.versions.forEach((version, index) => {
            this.itemsInDataBase.forEach((itemInDatabase, index) => {
                version.items.forEach((item, index) => {
                        this.insertItemInbox(item, itemInDatabase, version);
                    }
                );
            });
        });

grazie mille

CodePudding user response:

RxJS switchMap operator could be used where the inner observable depends on the outer observable. In your case, since both observables appear to be independent, you could use the forkJoin function.

forkJoin({
  items: this.getItems(),
  box: this.loadActiveBox()
}).pipe(
  tap({
    next: ({items, box}) => {
      this.itemsInDataBase = items;     // <-- are these needed?
      this.selectedBox = box;
    }
  })
).subscribe({
  next: ({items, box}) => {
    box?.versions.forEach(version =>
      items.forEach(itemInDatabase =>
        version.items.forEach(item =>
          this.insertItemInbox(item, itemInDatabase, version)
        )
      )
    )
  },
  error: (error: any) => {
    // handle errors
  }
});
  • Related