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"];
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.
I know there is
Rx.Observable.fromArray(imagepathes)
there is also something like
Rx.Observable.fromCallback(...)
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?
Thanks for any help.
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:
And with that, you can easily do something like this:
At first you need a function that will create a Observable or Promise for separate image:
Than you can use it to load all images
Or in short:
Here is the Angular / Typescript version to load an Image with RxJS:
The other RX based solutions here did not really work for me. Bogdan Savluk’s version did not work at all. Benjamin Gruenbaum’s version waits until an image is loaded before starting to load the next image so it gets really slow (correct me if I am wrong) Here is my solution which just compares the total amount of images with the number of already loaded images and if they are equal, the onNext() method of the returned Observable gets called with the array of images as an argument:
Usage:
I think you don't have to create an
Observable
yourself for this.