RXJS Angular - How to call a function at end of foreach loop that contains observables?
RXJS Angular - How to call a function at end of foreach loop that contains 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);
)
)
At the end of the foreach loop I'm checking the value of "i" and if it's greater than the list length, I call the function. The problem with this is that since I'm subscribing inside the loop, the value of I is not always in the correct order and the function is called early. How can I iterate through a foreach loop with the subscriptions inside, then call my function when the loop and subscriptions are complete?
2 Answers
2
Have you thought of forkJoin
? Might not be the cleanest but I think it can work. Also this can help waiting observable subscribe inside foreach to end
forkJoin
check the below code..
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);
);
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.