title: RxJS wait for second observable then retry original observable on error - TypeScript/Angular 2
body: <p>I am fairly new to Angular 2, TypeScript and RxJS and I am creating a simple application that leverages the Salesforce Ajax Toolkit connections library. </p>
  
  <p>I am trying to write a handler to catch when a token has expired any time a method from the connections library is called. I have created a service that essentially wraps the connections library to use observables. For example if we look at the insert function I have created my own wrapper function:</p>
  
  <pre><code> public insert(object: sforce.SObject): Observable&lt;any&gt; {
     return new Observable(observer =&gt; {
     // successfully inserted the record
     let insertSuccess = (result) =&gt; {
       observer.next(result);
       observer.complete();
      }
  
      // An error occured inserting the record
      let insertError = (result) =&gt; {
        // This does not work yet
        if (result.faultcode.indexOf('INVALID_SESSION_ID') != -1) {
          this.refreshToken();
        }
        else {
            observer.error(result);
        }
      }
  
      let callback = { onSuccess: insertSuccess, onFailure: insertError };
      sforce.connection.create([object], callback);
    });
  }
  </code></pre>
  
  <p>I have another function that refreshes the access token:</p>
  
  <pre><code> public refreshToken(): void {
      this.loginService.login().subscribe(
          response =&gt; {
  
              Globals.SESSION_TOKEN = response.access_token;
  
              //initialize the salesforce connection 
              this.init(Globals.SESSION_TOKEN, this.loginService.AuthParams.SOAP_URL);
          },
          error =&gt; {
  
          }
      );
  }
  </code></pre>
  
  <p>I essentially want the original <code>insert</code> function to wait for <code>refreshToken</code> to complete. If it is successful I want to retry the same insert again, otherwise I want the original insert observable to call <code>observer.error</code>. </p>
  
  <p>I've looked into <code>retry</code> and <code>retryWhen</code>, however I haven't been able to figure out how to implement it to wait for the <code>refreshToken()</code> function to complete. Any guidance or advice on this matter would be greatly appreciated. Thank you in advance.</p>