title: Subscribing multiple times to an observable rxjs
body: <p>I'm trying to achieve the following:</p>
  
  <p>I have an Observable that can be subscribed to multiple times, although I only want to do some processing once.</p>
  
  <pre><code>export class DataLoader
  {
      private loaded = false;
      private data: Data;
      private observable = null;
  
      load(): Observable&lt;Data&gt; {
          if(this.loaded) {
              console.log('Already loaded');
              return Observable.create((obs) =&gt; {
                  obs.next(this.data);
                  obs.complete();
              })
          }
  
          if(this.observable === null) {
              console.log('Creating observable');
              this.observable = Observable.create((obs) =&gt; {
  
                  console.log('firing xhr');
                  let xhr;
  
                  xhr.onload = () =&gt; {
                      this.data = data;
                      this.loaded = true;
                      obs.next(data);
                      obs.complete();
                      this.observable = null;
                  }
  
                  xhr.onerror = () =&gt; {
                      obs.error(error);
                      this.observable = null;
                  }
              });
          }
  
          return this.observable;
      }
  }
  </code></pre>
  
  <p>Lets say I use this DataLoader in 2 different places, the 'xhr' will only be done once.</p>
  
  <pre><code>...
  Dataloader.load().subscribe();
  ...
  #At another point in the code
  Dataloader.load().subscribe();
  ...
  </code></pre>
  
  <p>Console:</p>
  
  <pre><code>Creating observable
  firing xhr
  Already Loaded
  </code></pre>
  
  <p>This works correctly as long as the requests aren't fired off too quickly after each other.</p>
  
  <p>To demonstrate, lets put this in a for loop:</p>
  
  <pre><code>for(let i = 0; i&lt;10; i++) {
      DataLoader.load().subscribe();
  }
  </code></pre>
  
  <p>In this case the console looks like this:</p>
  
  <pre><code>Creating observable
  firing xhr
  firing xhr
  firing xhr
  firing xhr
  firing xhr
  firing xhr
  firing xhr
  firing xhr
  firing xhr
  firing xhr
  </code></pre>
  
  <p>How could I manage to use this in a for loop ?
  I've been looking into a Subject / BehaviourSubject but I cannot seem to make it work.</p>
  
  <p>Cookies for thoughs</p>