title: How can I avoid multiple nested subscriptions using RxJS operators?
body: <p>I am working on a file encryption and upload class using Angular. Many of these operations are async and therefore the methods I wrote are returning RxJS Observables.</p>
  
  <pre class="lang-js prettyprint-override"><code>// 1.
  private prepareUpload(file): Observable&lt;T&gt;;
  
  // 2.
  private encryptData(data, filekey): Observable&lt;T&gt;
  
  // 3.
  private uploadEncryptedData(formData, token, range): Observable&lt;T&gt;
  
  // 4.
  private completeUpload(updatedFilekey, token): Observable&lt;T&gt;
  </code></pre>
  
  <p>I want to encapsulate this logic in a public <code>upload(file)</code> method and I ended up using nested subscriptions and it works but I know that it is wrong and an anti-pattern in RxJS for several reasons. Here is a simplified version of the code:</p>
  
  <pre class="lang-js prettyprint-override"><code>public upload(file) {
      const gen = this.indexGenerator(); // generator function
  
      this.prepareUpload(file).subscribe(values =&gt; {
      const [response, filekey, data] = values;
  
      this.encryptData(data, filekey).subscribe(encryptedDataContainer =&gt; {
        const formData = this.prepareEncDataUpload(encryptedDataContainer.data, file.name)
        const range = this.getRange(file.size, gen.next().value);
  
        this.uploadEncryptedData(formData, response.token, range).subscribe(() =&gt; {
          if (range.isFinalPart) {
              this.completeUpload(encryptedDataContainer.updatedFilekey, response.token).subscribe(console.log);
          }
        });
  
      });
  
    });
  
  }
  </code></pre>
  
  <p>I failed to clean this code using combinations of several RxJS operators. My goal is to avoid nested subscriptions and instead return a single Observable from the public <code>upload()</code> method when the workflow is completed.</p>
  
  <p>Thanks!</p>