如何与 RxJs 异步加载图像并在所有加载时执行方法 [英] How to load images async with RxJs and perform a method when all loaded
问题描述
我正在尝试将基于 Promise 的代码转换为 RxJs,但很难理解 Rx,尤其是 RxJs.
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 paths = ["imagePath1","imagePath2"];
我喜欢用 Javascript 加载图片
And I like to load images in Javascript
var img = new Image();
img.src = imagePath;
image.onload // <- when this callback fires I'll add them to the images array
当所有图像都加载完毕时,我喜欢在其上执行一个方法.
and when all Images are loaded I like to execute a method on.
我知道有
Rx.Observable.fromArray(imagepathes)
还有类似的东西
Rx.Observable.fromCallback(...)
还有类似 flatMapLatest(...)
和 Rx.Observable.interval
或基于时间的调度器
and there is something like flatMapLatest(...)
And Rx.Observable.interval
or timebased scheduler
根据我的研究,我认为这些将是解决问题的成分,但我无法让组合发挥作用.
Based on my research I would assume that these would be the ingredients to solve it but I cannot get the composition to work.
那么如何从数组路径加载图像,以及在加载所有图像时执行基于间隔的方法?
So how do I load images from a array paths and when all images are loaded I execute a method based on an interval?
感谢您的帮助.
推荐答案
首先你需要一个函数来为单独的图像创建一个 Observable 或 Promise:
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
})
这篇关于如何与 RxJs 异步加载图像并在所有加载时执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!