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

前端 未结 6 910
臣服心动
臣服心动 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:35

    function loadImage(url){
        var img = new Image;
        img.src = url;
        var o = new Rx.Subject();
        img.onload = function(){ o.onNext(img); o.onCompleted(); };
        img.onerror = function(e){ o.onError(e); }; // no fromEvent for err handling
        return o;
    }
    
    var imageUrls = ['url1', 'url2', 'url3'];
    var joined = Rx.Observable.merge(imageUrls.map(loadImage));
    
    // consume one by one:
    joined.subscribe(function(item){
        // wait for item
    });
    
    joined.toArray().subscribe(function(arr){
        // access results array in arr
    });
    

    Or in short:

    var imageUrls = ['url1', 'url2', 'url3'];
    fromArray(imageUrls).map(url => {
        var img = new Image;
        img.src = url;
        return fromEvent(img, "load");
    }).toArray().subscribe(function(arr){
        // access results here
    });
    

提交回复
热议问题