title: Angular 7 RXJS Observables timer interval infinite loop start immediately
body: <p>I'm trying to make these RXJS observables work properly with Angular 7 but I can't figure out what's wrong.</p>
  
  <p>What I want to do is check is there is verify token state every 10 seconds for auth.</p>
  
  <pre><code>import {Injectable} from '@angular/core';
  import {HttpClient, HttpHeaders} from '@angular/common/http';
  import {interval, Observable, of, timer} from 'rxjs';
  import {concatMap, delay, flatMap, takeWhile, tap} from 'rxjs/operators';
  import {Token} from './Token';
  import {User} from './User';
  import {TokenFactory} from './factory/tokenfactory';
  
  const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };
  
  @Injectable({
    providedIn: 'root'
  })
  export class TokenService {
    private user;
    private token;
    private tokenLoginUrl = 'http://localhost:8080/login_check';
    private refreshTokenUrl = 'http://localhost:8080/token/refresh';
  
    constructor(private http: HttpClient) { }
  
    private verifyTokenState(): Observable&lt;any&gt; {
      if (!localStorage.getItem('token')) {
        this.getLoginInfo().subscribe(token =&gt; {
          this.token = TokenFactory.createToken(token.token, token.refresh_token, Date.now(), true);
          return of(this.token);
        });
        this.token = {};
        return of(this.token);
      }
  
      this.token = TokenFactory.getTokenFromLocalStorage();
      const timeElapsedInMinutes = (Date.now() - this.token.date_token) / 1000 / 60;
      console.log(timeElapsedInMinutes);
  
      if (timeElapsedInMinutes &gt;= 59) {
        this.getRefreshToken(this.token).subscribe(jsonToken =&gt; {
          this.token = TokenFactory.createToken(jsonToken.token, jsonToken.refresh_token, Date.now(), true);
          return of(this.token);
        });
      }
      return of(this.token);
    }
  
    private getLoginInfo(): Observable&lt;any&gt; {
      return this.http.post&lt;Token&gt;(this.tokenLoginUrl, this.user, httpOptions);
    }
  
    private getRefreshToken(token: Token): Observable&lt;any&gt; {
      return this.http.post&lt;Token&gt;(this.refreshTokenUrl, token, httpOptions);
    }
  
    public getToken() {
      return timer(0, 10000).pipe(
          flatMap(() =&gt; this.verifyTokenState()),
          takeWhile(() =&gt; this.token !== undefined &amp;&amp; !this.token.isValid)
      );
    }
  
    public setUser(user: User): void {
      this.user = user;
    }
  }
  </code></pre>
  
  <p>The issue I have is that when I call get TokenService.getToken() from inside another component (let's say in a login component after a user clicks the submit button) and I use <code>timer(0,10000)</code> the getLoginInfo() and 
  getRefreshToken() methods get called in an infinite loop and there are hundred of ajax calls fired.</p>
  
  <pre><code>public getToken() {
      return timer(0, 10000).pipe(
          flatMap(() =&gt; this.verifyTokenState()),
          takeWhile(() =&gt; this.token !== undefined &amp;&amp; !this.token.isValid)
      );
    }
  </code></pre>
  
  <p>The thing that I don't understand is that if I use 2000 instead of 0 as first parameter, everything works fine but it's not what I want.</p>
  
  <pre><code> public getToken() {
          return timer(2000, 10000).pipe(
              flatMap(() =&gt; this.verifyTokenState()),
              takeWhile(() =&gt; this.token !== undefined &amp;&amp; !this.token.isValid)
          );
        }
  </code></pre>
  
  <p>What I want exactly is for the observable to have intervals of 10 seconds between calls but I want it to start immediately. I also want to get an observable Token returned from the getToken() after its being returned from the verifyTokenSate() method. So what's wrong exactly? Is there a better way to do it? I want to do this in a reactive way without unsubscribe.</p>
  
  <p>The issues seem to happen in the AuthInterceptor after further invertigation. When I remove in from the module providers, everything is ok. Here is the AuthInterceptor:</p>
  
  <pre><code>import {Injectable} from '@angular/core';
  import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
  import {TokenService} from './token.service';
  import {Observable} from 'rxjs';
  import {map, mergeMap} from 'rxjs/operators';
  
  
  @Injectable()
  export class AuthInterceptor implements HttpInterceptor {
      private token;
      constructor(private auth: TokenService) { }
  
      intercept(
          req: HttpRequest&lt;any&gt;,
          next: HttpHandler
      ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
          let request = req.clone();
          this.auth.getToken().subscribe(t =&gt; {
              console.log(t);
              if (t.token) {
                  console.log('token valid');
                  request = req.clone({
                      setHeaders: { Authorization: `Bearer ${t.token}` }
                  });
              }
          });
  
          return next.handle(request);
      }
  }
  </code></pre>
  
  <p>So what's wrong inside the AuthInterceptor?</p>