Reading files in parallel with observables
<p>I am writing some application to read the selected files by the user and convert them to base64. I want to get notification when all the files are read in memory. For this purpose I am using <code>Observable</code> where handle the <code>onload</code> event of <code>FileReader</code> and send a complete notification. I am using <code>forkJoin</code> to run the operation in parallel.</p>

<p>Please see below the code where I am creating <code>Observable</code> and subscribing to it. </p>

<pre><code>onChange($event: any) {
  console.log('No of files selected: ' + $event.target.files.length);
  var observableBatch : any = [];

  var rawFiles = $event.target.files;
  for (var i = rawFiles.length - 1; i &gt;= 0; i--) {

      var reader = new FileReader(); 
      var file = rawFiles[i];
      var myobservable = Observable.create((observer: any) =&gt; {
        reader.onload = function (e: any) {
          var data = e.target;
          var imageSrc = data.result;
          console.log('File loaded succesfully.' );
          observer.next("File loaded");
          observer.complete();
        };
       });

      observableBatch.push(myobservable);
      reader.readAsArrayBuffer(file);

  }

  Observable.forkJoin(observableBatch)
  .subscribe(
      (m) =&gt; {
        console.log(m);
      },
      (e) =&gt; {
        console.log(e);
      },
      () =&gt; {
        console.log("All file(s) loading completed!!!");
      }
    ); 
}
</code></pre>

<p>Complete sample code is available in <a href="http://plnkr.co/edit/bSNj5Fhy441mpuN7rioS" rel="nofollow noreferrer">plunkr</a></p>

<p>When I select a single file, <code>onload</code> function is executed and I get the following console logs </p>

<p><a href="https://i.stack.imgur.com/iL55K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iL55K.png" alt="enter image description here"></a></p>

<p>However, when I select multiple files, <code>onload</code> gets executed only once and the batch operation is not completed. Please see the following console logs</p>

<p><a href="https://i.stack.imgur.com/ly9Wf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ly9Wf.png" alt="enter image description here"></a></p>

<p>Can somebody help me to understand where I am making the mistake?</p>