如何使用RxJs加载图像异步并在所有加载时执行方法 [英] How to load images async with RxJs and perform a method when all loaded
问题描述
我正在尝试将我的基于承诺的代码转换为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屋!