title: OkHttp token interceptor retries forever
body: <p>I'm making an OkHttp interceptor so it retry to sign in when any end point returns a 401 error, but the interceptor is looping forever.</p>
  
  <p>I've also tried to add a counter, but the counter resets itself every time.</p>
  
  <p>Here's my code:</p>
  
  <pre><code>object Service {
  
      private fun getOkHttpClient(): OkHttpClient {
          return OkHttpClient.Builder()
                  .addInterceptor(getLoggingInterceptor())
                  .addInterceptor(NetworkInterceptor())
                  .build()
      }
  
      private fun getRetrofit(): Retrofit {
          return Retrofit.Builder()
                  .addConverterFactory(GsonConverterFactory.create())
                  .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                  .client(getOkHttpClient())
                  .baseUrl(getBaseUrl())
                  .build()
      }
  }
  
  class NetworkInterceptor: Interceptor {
      var counter = 0
  
      override fun intercept(chain: Interceptor.Chain): Response? {
          val originalResponse = chain.proceed(chain.request())
  
          if (!originalResponse.isSuccessful &amp;&amp; originalResponse.code() == 401) {
              Log.e("NetworkInterceptor", "Network error 401. Counter = $counter")
              counter++
  
              val refreshedToken = refreshToken()
              Log.e("NetworkInterceptor", "refreshedToken = $refreshedToken")
          }
  
  
          return originalResponse
      }
  
      private fun refreshToken(): String {
          val context = MyApp.appContext
          val preferencesUtil = SharePreferencesUtils(context)
          val username = preferencesUtil.getUsername()
          val password = preferencesUtil.getPassword()
          val login = AuthService().loginSync(username, password).execute()
          return login.body()?.access_token!!
      }
  }
  </code></pre>
  
  <p>I have tried this with an Auth call being an RxJava <code>Single</code>, and a regular synchronous <code>Call&lt;&gt;</code></p>
  
  <p>In each case, the call happens forever, the 401 gets returned forever, and the counter always stays at 0.</p>
  
  <p>Any ideas on what I'm missing or doing wrong?</p>
  
  <p>Thank you very much!</p>