How to load images async with RxJs and perform a method when all loaded

前端 未结 6 908
臣服心动
臣服心动 2020-12-30 10:25

I am trying to convert my promise based code to RxJs but have a hard time to get my head around Rx especially RxJs.

I have a an array with paths.

var         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 10:28

    I think you don't have to create an Observable yourself for this.

    import { from, fromEvent } from 'rxjs';
    import { mergeMap, map, scan, filter } from 'rxjs/operators';
    
    const paths = ["imagePath1","imagePath2"];
    
    from(paths).pipe(
       mergeMap((path) => {
          const img = new Image();
    
          img.src = path;
          return fromEvent(img, 'load').pipe(
              map((e) => e.target)
          );
       }),
       scan((acc, curr) => [...acc, curr], []),
       filter((images) => images.length === paths.length)
    ).subscribe((images) => {
       // do what you want with images
    });
    

提交回复
热议问题