0

I have a case in which sometimes, an unknown amount of image links is returned. The image urls will always end with "p[page number].png", e.g.: p1.png, p2.png etc.

What I wanna do is loop through 10 max items and get the images from the server until the first 404 is returned - then I want to store the "problematic" item.

What is the best approach for this? I thought using forkJoin but then it emits all members of the array immediately and I don't have a trace of the "problematic" request.

Thanks!

Dan R.
  • 638
  • 5
  • 13

1 Answers1

1

I ended creating 2 observable from image load and error events, merging them and subscribing. For anyone who looks for a similar solution, here is the code:

updatePages(pdfPages: PdfImgPage[]){
    if(this.utilService.pagesAmountUnknown){
      let imgUrls = [];
      pdfPages.forEach(page => { imgUrls.push(this.utilService.getImgUrl(page.imgSrc))});
      let imgAmount = 0;
      from(imgUrls)
        .pipe(
          concatMap(url => {
            let img = new Image();
            img.src = url;
            const load = fromEvent(img, 'load').pipe();
            const error = fromEvent(img, 'error').pipe(switchMap(errorEvent => throwError(errorEvent)));
            return merge(load,error).pipe(take(1)); //to not wait for completion
          })
        )
        .subscribe(
          img => {
            this.logger.debug(`IMAGE in CONCAT MAP`, img);
            imgAmount++;
          },
          error => {
            this.logger.debug(`ERROR in CONCAT MAP imgAmount=${imgAmount}`, error);
            this.completeFunc(imgAmount);
          },
          () => {
            this.logger.debug(`COMPLETE in CONCAT MAP`);
          }
        );
    }
Dan R.
  • 638
  • 5
  • 13