javascript - RXJS Angular - איך לקרוא לפונקציה בסוף לולאת foreach שמכילה observables?


this.attachmentList.forEach((attachment, i) => {
    this.service.getPageOfAttachment().flatMap(response =>
        this.service.download((JSON.parse(response['Content']).mediaUrl)))
        .subscribe(response => {
            }, error => (console.log(error)),
            () => {
                if (i > this.attachmentList.length - 1) this.getPdfSharp(pdfSharpByteArray, attachment.entityName, i);
            })
})

בסוף לולאת foreach אני בודק את הערך של "i" ואם הוא גדול מאורך הרשימה, אני קורא לפונקציה. הבעיה בזה היא שבעקבות כך שאני מנוי בתוך הלולאה, הערך של i לא תמיד בסדר הנכון והפונקציה נקראת מוקדם. איך אני יכול לעבור על לולאת foreach עם המנויים בפנים, ואז לקרוא לפונקציה שלי כשהלולאה והמנויים מסתיימים?

תשובה #1

האם חשבת על forkJoin? אולי זה לא הכי נקי אבל אני חושב שזה יכול לעבוד. גם זה יכול לעזור לחכות לסאבסקירב של observable בתוך foreach להסתיים

תשובה #2

בדוק את הקוד למטה..

const _subscriptions = [];
  Observable.of(this.attachmentList)
    .subscribe((attachments) => {
      _subscriptions = attachments.map(element1 => {
        this.service.getPageOfAttachment()
          .flatMap(response => this.service.download((JSON.parse(response['Content']).mediaUrl)))
          .subscribe(response => { },
            error => (console.log(error)),
            completed => (console.log("completed...!!!")));
      });
    });
  Promise.all(_subscriptions)
    .then(() => {

        this.getPdfSharp(pdfSharpByteArray, attachment.entityName, i);
    });