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

前端 未结 6 912
臣服心动
臣服心动 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条回答
  •  甜味超标
    2020-12-30 10:39

    At first you need a function that will create a Observable or Promise for separate image:

    function loadImage(imagePath){
       return Rx.Observable.create(function(observer){
         var img = new Image();
         img.src = imagePath;
         img.onload = function(){
           observer.onNext(img);
           observer.onCompleted();
         }
         img.onError = function(err){
           observer.onError(err);
         }
       });
    }
    

    Than you can use it to load all images

    Rx.Observable
      .fromArray(imagepathes)
      .concatMap(loadImage) // or flatMap to get images in load order
      .toArray()
      .subscribe(function(images){
        // do something with loaded images
      })
    

提交回复
热议问题