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
I don't think you can do that easily with observables, as there's nothing there to indicate a finish (unless you have an initial size). Look at the other answers for the Rx version.
However, you can use an array of Promises:
/**
* Loads an image and returns a promise
* @param {string} url - URL of image to load
* @return {Promise} - Promise for an image once finished loading.
*/
function loadImageAsync(url) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.src = imagePath;
image.onload = function() { resolve(img); };
image.onerror = reject;
});
}
And with that, you can easily do something like this:
var imageUrls = ['url1', 'url2', 'url3'];
Promise.all(imageUrls.map(loadImageAsync))
.then(function(arrayOfImageElements) {
// All done!
});